Android Navigation Component and the BackStack

Using Android’s Navigation Component, I wanted to keep certain fragments from appearing on the backstack. Here’s how to do it.

Why?

There’s a couple of situations where you may not want a fragment to re-appear when navigating back. One is for a login/authentication fragment. e.g. you have a flow A -> login -> B, but navigating back from B should return to A, i.e. B -> A.

Another situation is A -> B1 <-> B2 -> C. For example, B1 is a map fragment, and B2 shows the same information in list form; the user may switch between B1 and B2 multiple times, before navigating to C to display an item’s full details. Navigating back from C should return to B1/B2, and then back to A. i.e. A -> B1 -> B2 -> B1 -> B2-> C -> B2 -> A.

How?

Taking the case of A -> Login -> B fragments, we modify the navigation action:

<action
  android:id="@+id/action_fragmentLogin_to_fragmentB"
  app:destination="@id/fragmentB"
/>

and add popUpTo to pop the current fragment off the backstack:

<action
  android:id="@+id/action_fragmentLogin_to_fragmentB"
  app:destination="@id/fragmentB"
  app:popUpTo="@id/fragmentLogin"
  app:popUpToInclusive="true"
/>

Now, navigating back from fragment B will return to fragment A.

Leave a comment