屏幕旋转后不显示片段

时间:2016-03-02 20:28:03

标签: android android-fragments screen-rotation

我有一个活动,ActivityA和3个片段,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,其中fragmentFragmentB的新实例或{ {1}}:

FragmentC

我在getSupportFragmentManager() .beginTransaction() .add(R.id.frame_layout_fragment, fragment) .addToBackStack(null) .commit(); 上按下后退按钮,显示FragmentC,并在FragmentB显示FragmentB时按下后退按钮,如预期的那样。当我在FragmentA时,我会旋转设备,FragmentC仍会按预期显示。

但是,当我使用后退按钮的2次按钮从FragmentC导航到FragmentC时,请将设备旋转两次,纵向 - >风景 - >纵向,添加FragmentA,添加FragmentB,然后我将设备旋转一次,我希望显示FragmentC,而是显示FragmentC。当我按下后退按钮一次时,没有任何反应。当我再次按下它时,它会导航回FragmentB。似乎FragmentA存在于后台堆栈中,但由于某种原因它不可见。

为什么FragmentC在这种情况下不可见?

1 个答案:

答案 0 :(得分:1)

我认为对另一个问题的回答也是你的回答:Difference between add(), replace(), and addToBackStack()

它说:

  

添加和替换之间的另一个重要区别是:替换   删除现有片段并添加新片段。这意味着何时   按下后退按钮,将创建被替换的片段   调用onCreateView。而添加保留了现有的   片段并添加一个新片段,表示现有片段将是   当有后退按钮时,它们不会处于“暂停”状态   没有为现有片段调用onCreateView(   在添加新片段之前存在的片段)。就......而言   片段的生命周期事件onPause,onResume,onCreateView等   在替换的情况下将调用生命周期事件,但它们不会   在添加时调用。

相关问题