我有一个包含片段的布局:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<fragment
android:id="@+id/ID"
class="com.teovald.app.MyFragment"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
<include
android:id="@+id/toolbar"
layout="@layout/toolbar" />
</FrameLayout>
我在这个片段onCreate方法中设置了这个使用setRetainInstance(true):
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setRetainInstance(true);
....}
最后,我还在其onCreate的活动中恢复了对这个片段的引用:
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
FragmentManager fragmentManager = getSupportFragmentManager();
mFragment = (MyFragment) fragmentManager.findFragmentById(R.id.ID);
...
}
但是,每次旋转设备时,都会调用onCreate of the activity,然后调用片段的onCreate!由于我将setRetainInstance设置为true,因此不应该发生。 这种行为有原因吗?
答案 0 :(得分:2)
我最近遇到过这个问题并且正在与它斗争几个小时,直到我发现在包含onSaveInstanceState中保留的非ui片段的Activity的代码(我从某些第三方库中复制)中没有调用super.onSaveInstanceState()
就像那样:
@Override
protected void onSaveInstanceState(Bundle outState) {
// Save the mapview state in a separate bundle parameter
final Bundle mapviewState = new Bundle();
mMapFragment.onSaveInstanceState(mapviewState);
outState.putBundle(BUNDLE_STATE_MAPVIEW, mapviewState);
}
所以我将缺少的电话添加为:
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save the mapview state in a separate bundle parameter
final Bundle mapviewState = new Bundle();
mMapFragment.onSaveInstanceState(mapviewState);
outState.putBundle(BUNDLE_STATE_MAPVIEW, mapviewState);
}
现在onCreate()在保留的片段中没有被调用两次。
我希望这会对某人有所帮助:)。