Reputation: 43
I am developing an application which contains NavigationDrawer with multiple tabs, which calls to different fragments.
Let's say I have fragments A, B, C.
On the creation of the activity the fragment container is populated with fragment A.
I want to somehow save a reference to this fragment that when I navigate to others fragment I will get back to fragment A through onBackPress().
It is important that fragment A will not be destroyed.
I tried implementing that with addToBackStack()
on the first transaction, but it only works when navigation to one other fragment:
A -> B -> onBackPress() -> A
But when I navigate to more it doesnt work properly:
A -> B -> C -> onBackPress() -> C
While the desired outcome is :
A -> B -> C -> onBackPress() -> A
I must be missing something and would appreciate some help with this.
Thank you
Upvotes: 2
Views: 152
Reputation: 843
override your onBackPressed().
Then use popBackstackImmediate with flag: POP_BACK_STACK_INCLUSIVE
This will popup all the backstack entries till the tag supplied in popBackstackImmediate() is found. So in short, in onBackPressed use popBackstackImmediate and supply it with Tag for Fragment A and also with flag POP_BACK_STACK_INCLUSIVE
Upvotes: 3
Reputation: 1255
yeah.. it is expected behavior. you have to add the addToBackStack() before every transaction to get the fragment while backpress
your flow should be like this
A (addToBackStack())-> B-> C -> onBackPress() -> B ->onBackPress() -> A.
Upvotes: 0