Disable adding fragment to backstack in Navigation Architecture Component

igor_rb picture igor_rb · Sep 27, 2018 · Viewed 14.1k times · Source

Suppose i have 4 fragments: A, B, C, X, and I can navigate between them in this way:

... -> A -> C -> X    and ... -> B -> C -> X

But when I'm in fragment X call mNavController.navigateUp() I want skip fragment C and go to fragment A or B. What I need to do?

UPD: I need solution only for Navigation Architecture Component https://developer.android.com/topic/libraries/architecture/navigation/ Thanks!

Answer

bentesha picture bentesha · Sep 27, 2018

Given R.id.fragmentC is the name of C destination, from X destination, you can do the following:

NavController controller = Navigation.findNavController(view);
controller.popBackStack(R.id.fragmentC, true);

This should pop all destinations off the stack until before C, and leave either A or B on top of the stack.