解决DialogFragment:Can not perform this action after onSaveInstanceState

问题:

Fragment的时候会偶尔出现错误:

Fatal Exception: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

在onSaveInstanceState行为之后,app执行某个不能响应的行为而导致异常发生。这里是指在执行onSaveInstanceState之后再调用FragmentTransaction的commit方法导致异常的发生

WechatIMG3039.jpeg

解决方案:

使用commitAllowingStateLoss即可。

下面从源码角度分析一下为什么。

WechatIMG150.jpeg
WechatIMG151.jpeg

首先:commit()和commitAllowingStateLoss() 都存在于package android.support.v4.app
FragmentTransaction类中

DialogFragment 中没有提供commitAllowingStateLoss(),只commit(),解决办法就是重写show方法 使用commitAllowingStateLoss()提交。


    public void show(FragmentManager manager, String tag) {
        this.mDismissed = false;
        this.mShownByMe = true;
        FragmentTransaction ft = manager.beginTransaction();
        ft.add(this, tag);
        ft.commit();
    }

try {
            var mDismissed: Field = DialogFragment::class.java.getDeclaredField("mDismissed")
            mDismissed.isAccessible = true
            mDismissed.set(this, false)

            var mShownByMe: Field = DialogFragment::class.java.getDeclaredField("mShownByMe")
            mShownByMe.isAccessible = true
            mShownByMe.set(this, true)
        } catch (e: Exception) {
            e.printStackTrace()
           
        }
        val ft: FragmentTransaction = manager.beginTransaction()
        ft.add(this, tag)
        ft.commitAllowingStateLoss()

修改:try catch 中 反射修改 private 字段 mShownByMe,mDismissed 之前获取异常 走到catch 未注意 已修改!

你可能感兴趣的:(解决DialogFragment:Can not perform this action after onSaveInstanceState)