报错:IllegalStateException: Can not perform this action after onSaveInstanceState
场景:Acitivity onCreate中用 postdelay去做了的 dialogfragment的show,且同时该Activity 进行了跳转b Activity的动作。因此Acitivty先调用了onSaveInstanceState,后调用了dialoggragment的show方法。
导致原因:dialoggragment的show方法调用了ft.commit
FragmentTransaction ft = manager.beginTransaction();
ft.add(this, tag);
ft.commit();
ft的具体实现是 FragmentManagerImpl ,commit会调用到checkStateLoss ;最终导致这个报错
private void checkStateLoss() {
if (isStateSaved()) {
throw new IllegalStateException(
"Can not perform this action after onSaveInstanceState");
}
}
解决方法:网上有很多解决方法,比如反射去修改show方法,让这个show去调用commitAllowingStateLoss;确实可以解决问题
public int commitAllowingStateLoss() {
return commitInternal(true);
}
public int commit() {
return commitInternal(false);
}
commitInternal的参数 就是来控制是否允许状态丢失 ,上面可以看到 commitAllowingStateLoss 传的true commit传的false;但我们也要想想系统为嘛要检测这个状态丢失,既然activity发生了跳转,系统已经调用了onSaveInstanceState
保存了当前状态,我们再去改变页面状态,是不是不太合适?与其通过反射去修改 show方法的实现,不如去避免在保存状态之后调用show方法。后来,我是在onRestart中调用的show方法。