在重建方向变化Android的碎片 [英] Android Fragments recreated on orientation change
问题描述
我正在开发一个应用程序,基本上有一个动作条。当我的应用程序启动时,该活动将创建片段,并将其连接到每个选项卡,所以当我转,我得到不同的看法。
I'm developing an app that basically has an ActionBar. When my app starts, the Activity creates the fragments and attaches them to each tab, so when I switch I get different views.
该问题,当我尝试旋转设备出现。一番挣扎后,我注意到,机器人将自动重新创建$ P $像这样pviously添加片段:
The problems arise when I try to rotate the device. After some struggle, I noticed that Android automatically recreates the previously added fragments like this:
SummaryFragment.onCreate(Bundle) line: 79
FragmentManagerImpl.moveToState(Fragment, int, int, int) line: 795
FragmentManagerImpl.moveToState(int, int, int, boolean) line: 1032
FragmentManagerImpl.moveToState(int, boolean) line: 1014
FragmentManagerImpl.dispatchCreate() line: 1761
DashboardActivity(Activity).onCreate(Bundle) line: 864
...
然后我重新创建片段像往常一样。所以,我有我希望正常工作,真正的片段的隐藏的Android创建的同行,让我的应用程序崩溃。我怎样才能避免这种情况?我已经试着拨打setRetainInstance(假)在SummaryFragment。
and then I recreate the fragments as usual. So I have the "real" fragments that I expect to work correctly and their "hidden" Android-created counterparts that make my app crash. How can I avoid this behavior? I already tried to call setRetainInstance(false) in the SummaryFragment.
感谢您
推荐答案
您需要检查一个savedInstanceState,如果它存在,不要创建你的片段。
You need to check for a savedInstanceState, and if it exists, don't create your fragments.
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (savedInstanceState == null) {
// Do your oncreate stuff because there is no bundle
}
// Do stuff that needs to be done even if there is a saved instance, or do nothing
}
这篇关于在重建方向变化Android的碎片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!