方向更改时不会恢复片段Backstack

时间:2015-09-17 18:44:30

标签: android android-layout android-fragments android-fragmentactivity

我有FragmentActivity,当用户浏览应用程序时,我将当前片段替换为用户选择的片段,并添加将事务添加到backstack。一切正常,用户可以通过按后退按钮返回到之前的片段。

当设备方向改变时出现问题:假设用户看到的第一个片段是A,那么他导航到B并从B导航到C. 在横向模式下,C内部的内容更受欢迎,并且C有一个特殊的横向布局,因此用户可以旋转设备。我希望用户能够使用新的方向进入C.相反,用户在横向中看到A.现在他需要再次从A导航到B再到C导航,以便能够在风景中看到C.

我希望在方向改变后保留背斜。

如果我在清单中的Activity的条目上使用configChange="orientation",则会保留backstack,但由于未重新创建片段,因此无法为新方向加载正确的布局。我敢打赌,当发生这种情况时,我可以使用一些讨厌的黑客来强制重新创建片段,但我认为应该有一个更好的解决方案来实现这么简单的事情。

显然我做错了,因为在this page中有一个解释说

  

- >片段管理器在两个上都调用onSaveInstanceState()   片段。
   - >活动和两个碎片都被销毁了    - >创建活动的新实例
   - >使用后台重新创建后栈   碎片的新实例

这听起来像我期望的行为,但这不会发生在我的应用中。我错过了什么吗?我怎样才能实现这种行为?

我在SO上看过一些类似的问题,但到目前为止,他们都没有帮助我解决这个问题。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:6)

我认为你在添加/替换片段之前没有检查savedInstanceState。试试这个:

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Check that the activity is using the layout version
    // with the fragment_container_main FrameLayout
    if (findViewById(R.id.fragment_container_main) != null) {


        // If we're being restored from a previous state,
        // then we don't need to do anything and should return or else
        // we could end up with overlapping fragments.
        if (savedInstanceState != null) { //Do nothing, Android has got your back.

        } else {
            FragmentOne fragmentOne = new FragmentOne();

            // Add the fragment to the fragment_container_main FrameLayout
            getFragmentManager().beginTransaction()
                    .add(R.id.fragment_container_main,
                            fragmentOne,
                            "FRAG_ONE").commit();
        }
    }
}

答案 1 :(得分:1)

结果是在方向改变后正在重新创建导航抽屉片段,因此它触发了onNavigationDrawerItemSelected,它总是替换android正在恢复的片段。我通过添加setRetainInstance(true)来修复它;在我的导航抽屉片段中。

相关问题