Victor Isarov
Victor Isarov

Reputation: 43

Using FragmentManager to always return to the same fragment

I am developing an application which contains NavigationDrawer with multiple tabs, which calls to different fragments.

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

Answers (2)

Rusheel Jain
Rusheel Jain

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

Dinesh Kannan
Dinesh Kannan

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

Related Questions