简体   繁体   English

Android:将两个或多个片段添加到相同的堆栈状态

[英]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 . 我有一个RelativeLayout容器的主要活动,在其中我使用FragmentManager加载不同的片段 Let's say i load fragment1 and fragment2 with two transactions. 假设我通过两个事务加载fragment1和fragment2。 In case of back button pressed, i want to return to the state when both fragment1 and fragment2 were not loaded. 如果按下后退按钮,我想返回到fragment1和fragment2都未加载的状态。 Is this possible? 这可能吗? I've tried to use the same name in the addToBackStack() method: 我试图在addToBackStack()方法中使用相同的名称:

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. 如果我按下后退按钮,fragment2首先消失,然后再次按下fragment1也消失。 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). 此时,当您按下“后退”按钮时,它将仅还原上一个事务(替换片段2)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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