在使用 DialogFragment 的过程中会偶现 java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState 的问题,具体错误日志如下
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:2080)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:2106)
at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:683)
at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:637)
at android.support.v4.app.DialogFragment.show(DialogFragment.java:144)
...
根据Google官方提供的方案,使用 commitAllowingStateLoss() 代替 commit() 可以解决此问题,关于 commitAllowingStateLoss() 官方的解释是
Like commit() but allows the commit to be executed after an activity's state is saved. This is dangerous because the commit can be lost if the activity needs to later be restored from its state, so this should only be used for cases where it is okay for the UI state to change unexpectedly on the user.
大概的意思是
在 Activity 的 onSaveInstanceState() 之后调用 commit() 会出错,因为 onSaveInstanceState() 是在 Activity 即将被销毁前调用,用来保存 Activity 的数据,如果在 onSaveInstanceState() 之后添加 Fragment 就会出错。解决办法就是把 commit() 替换成 commitAllowingStateLoss() 就行了,其效果是一样的。
对于DialogFragment 在调用 show() 方法出现此异常时可以使用
getSupportFragmentManager().beginTransaction().add(fragment, "tag").commitNowAllowingStateLoss();
DialogFragment 的 dismiss() 则替换成
dismissAllowingStateLoss();