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.
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.
Taking the case of A -> Login -> B fragments, we modify the navigation action:
and add popUpTo to pop the current fragment off the backstack:
Now, navigating back from fragment B will return to fragment A.
Leave a comment