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!
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.
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.
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>
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With