Ale*_*aux 4 android android-layout android-fragments android-fragmentactivity
我有一个FragmentActivity,当用户浏览应用程序时,我用当前用户选择的片段替换当前片段,然后添加将事务添加到backstack.一切正常,用户可以通过按后退按钮返回到之前的片段.
当设备方向改变时会出现问题:假设用户看到的第一个片段是A,那么他导航到B,从B导航到C.在横向模式中,C内部的内容更受欢迎,并且有一个特殊的景观布局对于C,所以用户旋转设备.我希望用户能够使用新的方向进入C. 相反,用户在横向中看到A. 现在他需要再次从A导航到B再到C导航,以便能够在风景中看到C.
我希望在方向改变后保留背斜.
如果我configChange="orientation"在清单中使用Activity的条目,则会保留backstack,但由于未重新创建片段,因此无法为新方向加载正确的布局.我敢打赌,当发生这种情况时,我可以使用一些讨厌的黑客来强制重新创建片段,但我认为应该有一个更好的解决方案来实现这么简单的事情.
显然我做错了,因为在这个页面中,有一个解释说
- > Fragment Manager在两个片段上调用onSaveInstanceState().
- >活动和两个碎片都被销毁
- >创建活动的新实例
- >使用碎片的新实例重新创建后堆栈
这听起来像我期望的行为,但这不会发生在我的应用程序中.我错过了什么吗?我怎样才能实现这种行为?
我在SO上看过一些类似的问题,但到目前为止他们都没有帮助我解决这个问题.任何帮助将不胜感激.
我想你在添加/替换片段之前没有检查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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
事实证明,导航抽屉片段在方向更改后被重新创建,因此它触发了 onNavigationDrawerItemSelected,它总是替换 android 正在恢复的片段。我通过添加 setRetainInstance(true); 修复了它 在我的导航抽屉片段中。
| 归档时间: |
|
| 查看次数: |
2363 次 |
| 最近记录: |