How to put back stack for Activity with multiple fragments?

Activity layout picture

Suppose I have an Activity that contains two FrameLayouts (let them be called FrameA and FrameB), which, in turn, contain a fragment (let them be called FragmentA1 and FragmentB1, respectively). Now I am committing a series of transactions of individual fragments using code similar to the following ...

getFragmentManager() .beginTransaction() .replace(frameId, fragment) .addToBackStack(null) .commit(); 

... so I replace FragmentA1 in FrameA with FragmentA2, then I replace FragmentB1 in FrameB with FragmentB2, and then replace FragmentA2 in FrameA with FragmentA3, and then replace FragmentB2 in Frame2 with FragmentB3, and the final state looks like the picture above (where you can see FragmentA3 and FragmentB3 only).

If I correctly understood how the back stack works, pressing back will alternate fragments of fragments between FrameA and FrameB (reflecting how I added them).

Does anyone know if it is possible to selectively output the last transaction to FrameA or FrameB? (i.e. if I clicked "Pop FrameA", then FrameA would be transferred back from FragmentA3 to FragmentA2, and instead, if I clicked "Pop FrameB", then FrameB would be transferred back from FragmentB3 to FragmentB2)

Addition: I know that I can add the last fragment to this FrameLayout using the FragmentManager.findFragmentById(int framelayoutId) method, but calling FragmentTransaction.remove(fragment).commit() removes only the fragment from the view and does not transfer the View back to the fragment, which he previously displayed.

+43
android android-fragments
Jan 07 2018-12-12T00:
source share
2 answers

Basically, no, for activity there is only one back stack.

You just need to implement your own individual stacks.

Starting with Android 4.0 (and the associated support library), there are APIs that should do this relatively easily - FragmentTransaction.detach (Fragment) allows you to put the fragment in the same state when in the back stack, and FragmentManager.saveFragmentInstanceState (Fragment) allows you to move on and completely discard the Fragment object. It is no coincidence that they are used to implement the ViewPager FragmentPagerAdapter and FragmentStatePagerAdapter respectively, so you can look at the code for them as an example of how to use them.

+22
Jan 17 2018-12-12T00:
source share
 FragmentManager.popBackStack(String name, FragmentManager.POP_BACK_STACK_INCLUSIVE) 

Here is the simplest answer, and the explanation is very clear:
Does it clean the stack of fragment correctly when exiting a deeply nested stack?

+10
Mar 06 '14 at 9:53
source share



All Articles