Lets say I have
A->B->C->D->E
In android back stack. I want to be able to get back to one of the following:
A->B->C
A->B
A
How can I achieve this? Hopefully without forcing back button clicks.
A task is a collection of activities that users interact with when trying to do something in your app. These activities are arranged in a stack—the back stack—in the order in which each activity is opened. For example, an email app might have one activity to show a list of new messages.
When you press the Back button, the current destination is popped off the top of the back stack, and you then navigate to the previous destination. The Up button appears in the app bar at the top of the screen. Within your app's task, the Up and Back buttons behave identically.
This is the default launch mode of activity (If not specified). It launches a new instance of an activity in the task from which it was launched. Numerous instances of the activity can be generated, and multiple instances of the activity can be assigned to the same or separate tasks.
Using the image and information from the official developers page on Android tasks and back stack you can see that of all other ways to launch an Activity you can ensure such behavior only using the FLAG_ACTIVITY_CLEAR_TOP
in your Intent flags.
Your regular back button proceeds as:
But when you specify this flag, you get a behavior like you need, as given by an example at this source:
consider a task consisting of the activities: A, B, C, D. If D calls startActivity() with an Intent that resolves to the component of activity B, then C and D will be finished and B receive the given Intent, resulting in the stack now being: A, B.
Use FLAG_ACTIVITY_CLEAR_TOP
flag.
Intent a = new Intent(this, A.class);
a.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(a);
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