最近公司項(xiàng)目里面有一些彈出的頁(yè)面咽块,采用了DialogFragment的方式剃盾,但是經(jīng)常在調(diào)用Dismiss的時(shí)候會(huì)報(bào)錯(cuò)
Can not perform this action after onSaveInstanceState
網(wǎng)上找了很多都是說(shuō)把commit()方法替換成 commitAllowingStateLoss()
還有說(shuō)用反射重寫(xiě)show()方法铲汪,目的也是為了把show()方法中的commit()方法替換成 commitAllowingStateLoss()
具體如下:
@Override
public void show(FragmentManager manager, String tag) {
// super.show(manager, tag);
try {
Class c = Class.forName("android.support.v4.app.DialogFragment");
Constructor con = c.getConstructor();
Object obj = con.newInstance();
Field dismissed = c.getDeclaredField("mDismissed");
dismissed.setAccessible(true);
dismissed.set(obj, false);
Field shownByMe = c.getDeclaredField("mShownByMe");
shownByMe.setAccessible(true);
shownByMe.set(obj, false);
} catch (Exception e) {
e.printStackTrace();
}
FragmentTransaction ft = manager.beginTransaction();
ft.add(this, tag);
ft.commitAllowingStateLoss();
}
但是還是不行,這時(shí)候我發(fā)現(xiàn)弄錯(cuò)了問(wèn)題所在跷跪,這里是在dissmiss()時(shí)報(bào)錯(cuò)的柠傍,我改show()方法有啥用麸俘。
然后翻看dissmiss()的源碼發(fā)現(xiàn),它其實(shí)調(diào)用的是this.dismissInternal(false);
void dismissInternal(boolean allowStateLoss) {
if (!this.mDismissed) {
this.mDismissed = true;
this.mShownByMe = false;
if (this.mDialog != null) {
this.mDialog.dismiss();
}
this.mViewDestroyed = true;
if (this.mBackStackId >= 0) {
this.getFragmentManager().popBackStack(this.mBackStackId, 1);
this.mBackStackId = -1;
} else {
FragmentTransaction ft = this.getFragmentManager().beginTransaction();
ft.remove(this);
if (allowStateLoss) {
ft.commitAllowingStateLoss();
} else {
ft.commit();
}
}
}
}
在這里看到了熟悉的commitAllowingStateLoss()和commit()惧笛,是通過(guò)allowStateLoss來(lái)判斷調(diào)用哪個(gè)从媚,很顯然,問(wèn)題的關(guān)鍵就再allowStateLoss這個(gè)參數(shù)患整。
然后又找到了領(lǐng)一個(gè)方法dismissAllowingStateLoss()拜效,把用到dissmiss的地方,換成它就好了