Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add animation to changing fragments using Navigation Component?

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

like image 228
Oleh Liskovych Avatar asked Oct 13 '18 15:10

Oleh Liskovych


People also ask

Can navigation component be used for activities?

The Navigation component uses an activity as a host for navigation and swaps individual fragments into that host as your users navigate through your app. Before you can start to layout out your app's navigation visually, you need to configure a NavHost inside of the activity that is going to host this graph.

What is transition animation in Android?

Android's transition framework allows you to animate all kinds of motion in your UI by simply providing the starting layout and the ending layout.


2 Answers

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

like image 98
Eric Martori Avatar answered Oct 16 '22 10:10

Eric Martori


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());
like image 31
Ajith Ramsaran Avatar answered Oct 16 '22 08:10

Ajith Ramsaran