How to add animation to changing fragments using Navigation Component?

13,374

Solution 1

In the Navigation Component documentation(https://developer.android.com/topic/libraries/architecture/navigation/navigation-implementing) in the section: Create a transition between destinations (it's near the end of the document) you have it explained in detail.

You can either add them using the editor by selecting the arrow of the desired transition and then selecting the animations in the Animations section of the Attributes tab.

Or by referencing the animations in the xml file like in the example:

<fragment
    android:id="@+id/specifyAmountFragment"
    android:name="com.example.buybuddy.buybuddy.SpecifyAmountFragment"
    android:label="fragment_specify_amount"
    tools:layout="@layout/fragment_specify_amount">
    <action
        android:id="@+id/confirmationAction"
        app:destination="@id/confirmationFragment"
        app:enterAnim="@anim/slide_in_right"
        app:exitAnim="@anim/slide_out_left"
        app:popEnterAnim="@anim/slide_in_left"
        app:popExitAnim="@anim/slide_out_right" />
 </fragment>

You can use regular anim resources for this animations

Solution 2

If you want to add animation through programmatically, use NavOptions (here).

NavOptions.Builder navBuilder =  new NavOptions.Builder();
navBuilder.setEnterAnim(R.anim.slide_left).setExitAnim(R.anim.slide_right).setPopEnterAnim(R.anim.slide_left).setPopExitAnim(R.anim.slide_right);

//Inside Activity
NavController navController = Navigation.findNavController(this, R.id.nav_host_fragment);
navController.navigate(R.id.destinationFragmentId,null,navBuilder.build());
//Inside Fragment
NavHostFragment.findNavController(YoutFragment.this)
                            .navigate(R.id.destinationFragmentId, null, navBuilder.build());
Share:
13,374
Oleh Liskovych
Author by

Oleh Liskovych

Updated on July 11, 2022

Comments

  • Oleh Liskovych
    Oleh Liskovych almost 2 years

    How to add animation to changing fragments using Navigation Architecture Component?

  • Harvey
    Harvey over 4 years
    hmm. But seems like NavOption doesn't allow us to specify the animation duration. All we can do is set the duration in every anim file.
  • Mohamed Ibrahim
    Mohamed Ibrahim over 3 years
    is there a way to do Circular Reveal transition with it