Fragment之 IllegalStateException: Can not perform this action after onSaveInstanceState:
今天使用Fragment的时候,出现了这个错误 IllegalStateException: Can not perform this action after onSaveInstanceState:E/AndroidRuntime(12747): Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1314)
at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1325)
使用FragmentTransition的 commit方法添加一个Fragment的时候出现的,后来发现官方的API已经对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.
参见:http://developer.android.com/reference/android/app/FragmentTransaction.html#commit()
意思是说 commit方法是在Activity的onSaveInstanceState()之后调用的,这样会出错,因为onSaveInstanceState方法是在该Activity即将被销毁前调用,来保存Activity数据的,如果在保存状态后再给它添加Fragment就会出错。如果允许丢失提交的话,可以把commit()方法替换成 commitAllowingStateLoss()就行了。