How to add animation to changing fragments using Navigation Architecture Component?
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.
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.
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
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With