Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable adding fragment to backstack in Navigation Architecture Component

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!

like image 748
igor_rb Avatar asked Sep 27 '18 09:09

igor_rb


People also ask

What is Backstack in fragments?

Calling addToBackStack() commits the transaction to the back stack. The user can later reverse the transaction and bring back the previous fragment by pressing the Back button. If you added or removed multiple fragments within a single transaction, all of those operations are undone when the back stack is popped.

What is popUpToInclusive?

popUpTo and popUpToInclusive For example, if your app has an initial login flow, once a user has logged in, you should pop all of the login-related destinations off of the back stack so that the Back button doesn't take users back into the login flow.


3 Answers

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>
like image 102
Viacheslav Avatar answered Oct 19 '22 20:10

Viacheslav


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.

like image 30
bentesha Avatar answered Oct 19 '22 18:10

bentesha


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.

like image 5
Muhammad Maqsood Avatar answered Oct 19 '22 19:10

Muhammad Maqsood