Disable adding fragment to backstack in Navigation Architecture Component

Alternatively you could use app:popUpTo and app:popUpToInclusive attributes in navigation xml resource to cleanup back stack automatically when perform certain transactions, so back / up button will bring your user to the root fragment.

<fragment
    android:id="@+id/fragment1"
    android:name="com.package.Fragment1"
    android:label="Fragment 1">

    <action
        android:id="@+id/action_fragment1_to_fragment2"
        app:destination="@id/fragment2"
        app:popUpTo="@id/fragment1"
        app:popUpToInclusive="true / false" />

</fragment>

As mentioned by @bentesha this works in this way that it will pop fragments until fragmentC inclusively.

You can also achieve this as below:

NavController controller = Navigation.findNavController(view);
controller.popBackStack(R.id.fragmentA, false);

OR

NavController controller = Navigation.findNavController(view);
controller.popBackStack(R.id.fragmentB, false);

And this will pop up to fragmentA/fragmentB exclusively, I think it's most descriptive way for yourself and for others to understand.


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.