DialogFragment Can not perform this action after onSaveInstanceState 问题的原因与解决

329 阅读1分钟

为了解决 Activity 调用 onSaveInstanceState 以后又调用了 DialogFragment.show 方法, 出现的 Can not perform this action after onSaveInstanceState, 我们可以在 DialogFragment 下重写 showshowNow 方法,使其支持 commitAllowingStateLoss

/**
 * 为了解决:mainActivity调用onSaveInstanceState以后又调用了show方法,
 * 出现的Can not perform this action after onSaveInstanceState
 * 这个异常(不应该用commit ,而是用commitAllowingStateLoss)
 * @param manager
 * @param tag
 */
override fun show(manager: FragmentManager, tag: String?) {
    val mClass = DialogFragment::class.java
    kotlin.runCatching {
        val dismissed = mClass.getDeclaredField("mDismissed")
        dismissed.isAccessible=true
        dismissed.set(this,false)
    }
    kotlin.runCatching {
        val shownByMe = mClass.getDeclaredField("mShownByMe")
        shownByMe.isAccessible=true
        shownByMe.set(this,true)
    }
    val ft = manager.beginTransaction()
    ft.add(this, tag)
    ft.commitAllowingStateLoss()
}

override fun showNow(manager: FragmentManager, tag: String?) {
    val mClass = DialogFragment::class.java
    kotlin.runCatching {
        val dismissed = mClass.getDeclaredField("mDismissed")
        dismissed.isAccessible=true
        dismissed.set(this,false)
    }
    kotlin.runCatching {
        val shownByMe = mClass.getDeclaredField("mShownByMe")
        shownByMe.isAccessible=true
        shownByMe.set(this,true)
    }
    val ft = manager.beginTransaction()
    ft.add(this, tag)
    ft.commitAllowingStateLoss()
}