How to avoid fragment recreation using navigation architecture component?

2.2k views Asked by At

I have 4 fragments in a drawer, lets call them fragment A, B, C, D. I use navigation architecture to bind my fragments with the drawer.

Fragment A is my entry point and from there I can navigate anywhere on the drawer.

Suppose I take the path A > B > C > B > C

If I press back from C, it goes to B then to C again and then to B and finally to A, but I don't want that.

When I press the back button from C, I want it to just go back to B then A without recreating fragments that are already in the back stack. Can someone please help on how to achieve this ?

1

There are 1 answers

1
Siddharth Kamaria On

When I press the back button from C, I want it to just go back to B then A without recreating fragments that are already in the back stack.

When you are navigating to a destination, you can pop the old instance of the destination from the back stack. Just add the pop inclusive to all your action in nav graph.

<!-- Add this in the actions navigating to B -->
app:popUpTo="@id/B" 
app:popUpToInclusive="true"

Explanation

What the above pop behavior will do is, when you are navigating from, say C > B, it will pop everything till B (inclusive) from the back stack and add the latest instance of B on the back stack.

A > B > C > B > C will have a back stack:

A
A, B
A, B, C
A, B
A, B, C

Note: The inherent assumption here is that this is not a valid case in your example. A > B > C > D > B > C leads to a back tracking of C > B > D > A. Please be aware that in the above solution when you navigate to second B, it will pop out D from you back stack too!