简体   繁体   中英

Android: add two or more fragments to the same backstack state

I have a main activity with a RelativeLayout container where i load different fragments using the FragmentManager . Let's say i load fragment1 and fragment2 with two transactions. In case of back button pressed, i want to return to the state when both fragment1 and fragment2 were not loaded. Is this possible? I've tried to use the same name in the addToBackStack() method:

mFragmentManager.beginTransaction().replace(R.id.activity_main, fragment1).addToBackStack("SameState").commit();

mFragmentManager.beginTransaction().add(R.id.activity_main, fragment2).addToBackStack("SameState").commit();

but this doesn't work. If i press the back button fragment2 disappears first, then pressing again fragment1 goes away too. Any suggestion?

Try this:

mFragmentManager.beginTransaction()
 .replace(R.id.activity_main,fragment1)
 .addToBackStack(null)
 .commit();

getSupportFragmentManager().popBackStack(); // Pop the first transaction
mFragmentManager.beginTransaction()
 .replace(R.id.activity_main,fragment2)
 .addToBackStack(null)
 .commit();

At this point, when you press the back button, it will simply revert the last transaction (fragment2 replacing).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM