Search code examples
androidandroid-transitionsandroid-architecture-navigationandroid-jetpack-navigation

How to add transition animation to all actions in Jetpack Navigation?


To add transition animation in Jetpack navigation, we can add animation attributes to action like below in xml

<action
    android:id="@+id/action_fragment1_to_fragment2"
    app:destination="@id/fragment2"
    app:enterAnim="@anim/slide_in_right"
    app:exitAnim="@anim/slide_out_left"
    app:popEnterAnim="@anim/slide_in_left"
    app:popExitAnim="@anim/slide_out_right"/>

To make it pragmatically

NavOptions navOptions = new NavOptions.Builder()
   .setEnterAnim(R.anim.slide_in_right)
   .setExitAnim(R.anim.slide_out_left)
   .setPopEnterAnim(R.anim.slide_in_left)
   .setPopExitAnim(R.anim.slide_out_right)
   .build();

But in my case I have so many fragments in the project and it would be a tedious task to define animation over every single actions,

Is there anyway we can define animation for every action at once and it will apply transition animation to every actions?

Thanks in advance!


Solution

  • I have created a few extension method to manage animation of each navigation actions.

    fun NavController.safeNavigate(
        @IdRes direction: Int,
        popupTo: Int? = null,
        inclusive: Boolean = false,
        args: Bundle? = null,
        options: NavOptions = buildAnimOptions(popupTo, inclusive)
    ) {
        navigate(direction, args, options)
    }
    
    fun NavController.safeNavigate(
        navDirections: NavDirections,
        popupTo: Int? = null,
        inclusive: Boolean = false,
        options: NavOptions = buildAnimOptions(popupTo, inclusive)
    ) {
        navigate(navDirections, options)
    }
    
    private fun buildAnimOptions(
        popupTo: Int?,
        inclusive: Boolean = false
    ): NavOptions {
        val builder = NavOptions.Builder()
            .setEnterAnim(R.anim.right_in)
            .setExitAnim(R.anim.left_out)
            .setPopEnterAnim(R.anim.left_in)
            .setPopExitAnim(R.anim.right_out)
        if (popupTo != null) builder.setPopUpTo(popupTo, inclusive)
        return builder.build()
    }