我有一个 Activity ActivityA
和 3 个 fragment FragmentA
、FragmentB
和 FragmentC
。
要添加 FragmentA,我使用 replace
,其中 fragment
是 FragmentA
的新实例:
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frame_layout_fragment, fragment)
.commit();
在 ActivityA 的 onCreate
方法中,我检查了 FragmentA
的创建:
if (savedInstanceState == null) {
FragmentA fragmentA = FragmentA.newInstance();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.frame_layout_fragment, fragmentA)
.commit();
}
要添加 FragmentB
和 FragmentC
,我使用 add
和 addToBackStack
,其中 fragment
是 FragmentB
或 FragmentC
的新实例:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.frame_layout_fragment, fragment)
.addToBackStack(null)
.commit();
我在 FragmentC
上按后退按钮,它显示 FragmentB
,在 FragmentB
上按后退按钮显示 FragmentA
,正如预期的那样。当我在 FragmentC
上时,我旋转了设备,并且 FragmentC
仍然按预期显示。
但是,当我使用 2 次后退按钮从 FragmentC
导航到 FragmentA
时,然后旋转设备两次,纵向 -> 横向 -> 纵向,添加FragmentB
,添加FragmentC
,然后我旋转设备一次,我希望显示FragmentC
,但显示FragmentB
.当我按一次后退按钮时,没有任何反应。当我再次按下它时,它会导航回 FragmentA
。似乎 FragmentC
出现在返回堆栈中,但由于某种原因它不可见。
为什么 FragmentC
在这种情况下不可见?
最佳答案
我认为另一个问题的答案也是你的答案:Difference between add(), replace(), and addToBackStack()
它说:
One more importance difference between add and replace is: replace removes the existing fragment and adds a new fragment. This means when you press back button the fragment that got replaced will be created with its onCreateView being invoked. Whereas add retains the existing fragments and adds a new fragment that means existing fragment will be active and they wont be in 'paused' state hence when a back button is pressed onCreateView is not called for the existing fragment(the fragment which was there before new fragment was added). In terms of fragment's life cycle events onPause, onResume, onCreateView and other life cycle events will be invoked in case of replace but they wont be invoked in case of add.
关于android - 屏幕旋转后不显示 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35757425/