如何解决Can not perform this action after onSaveInstanceState

如何解决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在后台情况下返回前台,也会立即弹窗。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容