android - 屏幕旋转后不显示 fragment

标签 android android-fragments screen-rotation

我有一个 Activity ActivityA 和 3 个 fragment FragmentAFragmentBFragmentC

要添加 FragmentA,我使用 replace,其中 fragmentFragmentA 的新实例:

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();
}

要添加 FragmentBFragmentC,我使用 addaddToBackStack,其中 fragmentFragmentBFragmentC 的新实例:

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/

相关文章:

android - 如何在Android中将操作栏的标题设置在中心

android - ListView 中的 onItemClick 不起作用

android - 如何在android应用中实现Navigation Drawer + 全新的Toolbar?

android - 将 fragment 动态添加到 fragment 中

ios - 未在模态呈现的 View Controller 中调用 willRotateToInterfaceOrientation

android - setStat() 不更新屏幕

java - Android:以事务方式将大量文件移动到 SD 卡?

android - onCreate 中的 fragment 创建?

java - 屏幕旋转后恢复 fragment 中微调器的位置

android - 屏幕旋转后出现 nullPointerException