今天遇到了一个这样的问题,我写了一个MainActivity,里面有一个NavigationDrawer,其中的内容自然是使用的Fragment,当我在MainActivity上弹出一个Dialog样式的Activity并且这个Activity将要关闭的时候,程序会Crash掉,报出一个 java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState的错误,通过十几个Log连续输出跟踪,发现时在修改Fragment的commit的时候出现了异常,查看开发者文档,是这样写的
public abstract int commit ()
Schedules a commit of this transaction. The commit does not happen immediately; it will be scheduled as work on the main thread to be done the next time that thread is ready.
A transaction can only be committed with this method prior to its containing activity saving its state. If the commit is attempted after that point, an exception will be thrown. This is because the state after the commit can be lost if the activity needs to be restored from its state. See commitAllowingStateLoss()
for situations where it may be okay to lose the commit.
Returns
- Returns the identifier of this transaction's back stack entry, if
addToBackStack(String)
had been called. Otherwise, returns a negative number.
首先,他说commit不是立即执行,而是当主线程在下一次准备好的时候进行修改,也就是说,这个函数只是把请求放到队列中去。注意中间的部分,他说commit操作必须在父容器saving state之前,因为当父容器saving state,意味着父容器可能会被销毁,这个时候这个commit可能会变成无效的。
回过头来看我们的错误,应该就是这个问题,所以下面的的解决方式就是使用commitAllowingStateLoss()方法,我们再看一下这个方法的介绍
public abstract int 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.