原因
Activity异常销毁重新创建,一方面恢复了之前的Fragment,又重新加载Fragment,所以导致重叠
FragmentActivity异常销毁时保存了Fragment的状态:
static final String FRAGMENTS_TAG = "android:support:fragments";
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
markState(getSupportFragmentManager(), Lifecycle.State.CREATED);
Parcelable p = mFragments.saveAllState();
if (p != null) {
outState.putParcelable(FRAGMENTS_TAG, p);//保存了fragment
}
}
FragmentActivity重新创建时:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
Parcelable p = savedInstanceState.getParcelable(FRAGMENTS_TAG);
mFragments.restoreAllState(p, nc != null ? nc.fragments : null);//还原Fragment
}
}
解决方案
在Activity的onCreate方法调用父类onCreate方法之前移除key为FRAGMENTS_TAG的fragment数据
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
//必须在super 之前调用,不然无效。因为那时候fragment已经被恢复了。
if (savedInstanceState != null) {
// FRAGMENTS_TAG
savedInstanceState.remove("android:support:fragments");
savedInstanceState.remove("android:fragments");
}
super.onCreate(savedInstanceState);
}
网友评论