如何解决Can not perform this action after onSaveInstanceState
先分析问题发生原因
private void checkStateLoss() {
if (isStateSaved()) {
throw new IllegalStateException(
"Can not perform this action after onSaveInstanceState");
}
}
public boolean isStateSaved() {
// See saveAllState() for the explanation of this. We do this for
// all platform versions, to keep our behavior more consistent between
// them.
return mStateSaved ||mStopped;
}
通过分析源码我们找到,当activity执行了onSaveInstanceState或onStop方法后,操作子fragment系统会检测当前状态并抛出异常。
解决方法:
配合Lifecycle,我们只需要重写添加:
lifecycleScope?.launchWhenResumed{
//show fragment dialog
}
这样系统会自动在resumed后再弹出dialogfragment,也能避免Can not perform this action after onSaveInstanceState
这样即使是activity在后台情况下返回前台,也会立即弹窗。
网友评论