Search code examples
androidandroid-architecture-navigationandroid-navigation

How to navigate from a fragment to another clearing some other fragments from the stack?


I have the following navigation graph

Frag A  -->  Frag B --> Frag C --> -->  Frag D
        \                            /
         ->  Frag E  <---------------
                     \
                      -> Frag F

My current stack is [Frag A, Frag B, Frag C and Frag D]. Knowing that my current destination is Frag D and that I want to navigate from Frag D to Frag E clearing Frag B, Frag C and Frag D from the stack, how can one do it?


Current stack: [Frag A, Frag B, Frag C and Frag D]

Intent: navigate to Frag E clearing [Frag B, Frag C and Frag D] from the stack

resulting stack: [Frag A and Frag E]


Solution

  • if you are navigating through navigation graph actions, that would be an easy task by specifying that you need your action to popUpTo certain fragment like this :

     <fragment
            android:id="@+id/D_Frag"
            ...           
                <action
                android:id="@+id/action_DFrag_To_EFrag"
                app:destination="@+id/E_Frag"
                app:popUpTo="@+id/B_Frag"
                app:popUpToInclusive="true"
                />
            ...
        </fragment>
    

    where popUpToInclusive flag means (do you want to popUpTo B_Frag including B_Frag(True) or excluding it(False)).

    this action will pop all fragments from top stack until it reaches B_Frag, and then go the destination E_Frag.

    and by

    navigating through navigation graph actions

    I mean that you use likes of this code line in D Fragment to navigate

    NavHostFragment.findNavController(DFrag.this)
                        .navigate(R.id.action_DFrag_To_EFrag);
    

    N.B : three dots in code (...) means I don't care what code is written there and you may delete the three dots and include whatever you want