Android Navigation Component pop to transition issue

jaydeep_gedia picture jaydeep_gedia · Dec 30, 2018 · Viewed 8.2k times · Source

I have 2 actions

Action1

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

Action2

<action
        android:id="@+id/actionIntroAskLocationToLogin"
        app:destination="@id/loginFragment"
        app:enterAnim="@anim/slide_in_right"
        app:exitAnim="@anim/slide_out_left"
        app:popEnterAnim="@anim/slide_in_right"
        app:popExitAnim="@anim/fade_out"
        app:popUpTo="@+id/app_main_navigation" />

What i want is when the second action is triggered i want to clear the back stack and set only loginFragment to remain in the stack.

just one problem is when i perform the Action2, 'slide_out_right' is performed as exit animation

I understand that if we pop the fragment from the stack the 'popExitAnim' of action1 will be triggered instead of 'exitAnim' of action2.

but i want to know how can I make the fragment perform slide_out_left animation for exiting and also pop it out of the stack.

Answer

maxbeaudoin picture maxbeaudoin · Apr 24, 2019

I ended up overriding onCreateAnimation in the fragment that calls navigate. This exemple shows how to navigate through nested nav graphs by ID and replace the pop exit animation (or popExitAnim) conditionnally.

override fun onCreateAnimation(transit: Int, enter: Boolean, nextAnim: Int): Animation? {
    val navController = findNavController()
    val graph = navController.graph.findNode(R.id.onboardingGraph) as NavGraph
    val dest = graph.findNode(R.id.confirmationFragment)
    if (!enter && dest != null && navController.currentDestination?.id == dest.id) {
        return AnimationUtils.loadAnimation(requireContext(), R.anim.slide_out_left)
    }
    return super.onCreateAnimation(transit, enter, nextAnim)
}

Note that this particular situation is partly due to the directional nature of slide animations.