I would like to modify the back stack in my Android application as such:
Right now, here is the flow:
A -> B -> C -> D -> E -> F
I want to be able to modify the back stack, so that when the user goes to activity F, D and E are erased from the stack. so the flow is F -> C if the user hits the back.
Also, from F, the user is able to go to activity B, this should erase C, D, E, and F as well.
I’ve seen some information on being able to clear the stack, or remove the top item, but I want to remove a number of items from the stack, when an activity is triggered.
Any help is appreciated, thanks very much.
You can build an intent with the flag
intent.FLAG_ACTIVITY_CLEAR_TOPfrom F to C. Then you will have to call startActivity() with the intent and trigger this to occur onBackPressed or something similar.See this answer, which also deals with ensuring that C won’t be restarted when you navigate back to it: https://stackoverflow.com/a/11347608/1003511
What
FLAG_ACTIVITY_CLEAR_TOPwill do is go go back to the most recent instance of activity C on the stack and then clear everything which is above it. However, this can cause the activity to be re-created. If you want to ensure it will be the same instance of the activity, useFLAG_ACTIVITY_SINGLE_TOPas well. From the documentation:Edit: Here is a code sample similar to what you want to do:
code sample source: https://stackoverflow.com/a/9398171/1003511