2

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

scott_lotus
  • 3,171
  • 22
  • 51
  • 69

2 Answers2

3

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

Rusheel Jain
  • 843
  • 6
  • 20
0

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.

Dinesh Kannan
  • 1,255
  • 13
  • 32