How to transform the floating action buttons to full screen and open new activity in android studio and vice versa?

Viewed 717

I would like to transition between two activities(Activity A and Activity B).Activity A contains a floating action button (FAB) on the bottom right. When the FAB is clicked, the FAB should transform into a new surface that spans the entire screen and that entire screen is Activity B. When the back button is pressed in Activity B then the whole screen surface should shrink back to FAB which is now Activity A. How can I do that?

1 Answers

Yes. You can actually do that with the Shared Element transitions in android.

It's easy to use. Just follow the steps:

  1. Enable Window Content Transitions in your style XML which you are using in the activity.

    <style name="AppTheme" parent="Theme.MaterialComponents.DayNight.NoActionBar">
          <!-- Customize your theme here. -->
          <item name="colorPrimary">@color/colorPrimary</item>
          <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
          <item name="colorAccent">@color/colorAccent</item>
    
          <!-- Define the attribute here. -->
          <item name="android:windowContentTransitions">true</item>
    </style>
    
  2. Set the common transition name in both your views. For example, You want to animate FAB to the full screen view of Activity B. So you have to apply the transition name to your FAB & the parent view of Activity B.

    <LinearLayout ...>
    
    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="end|bottom"
        android:layout_margin="16dp" 
        android:transitionName="transition_fab"/>
    
        ...
    </LinearLayout>
    

Now in your activity xml of Activity B.

<RelativeLayout 
    android:id="@+id/root_view"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:transitionName="transition_fab"/>

<TextView
    ... />

</RelativeLayout>
  1. Now, Open Activity with the Element Transition, Create ActivityOptions in Activity A and put the common object name in it like shown below.

    FloatingActionButton fab = findViewById(R.id.fab);
    
    Intent intent = new Intent(ActivityA.this, ActivityB.class);
    ActivityOptions options = ActivityOptions
         .makeSceneTransitionAnimation(this, fab, "transition_fab");
    startActivity(intent, options.toBundle());
    

And that's it! You can now see your FAB animating from Activity A to the Full screen in Activity B.

You can find more details about the Shared Element Transition here - Android Shared element transitions

Related