解決IllegalStateException: Can not perform this action after onSaveInstanceState
? 今天使用Fragment的時候,出現了這個錯誤 IllegalStateException: Can not perform this action after onSaveInstanceState。
? 問題是在使用FragmentTransition的 commit方法添加一個Fragment的時候出現的,官網(https://developer.android.com/reference/android/app/FragmentTransaction.html#commitAllowingStateLoss())中有如下說明:
- commit
added in API level 11
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 | |
---|---|
int |
Returns the identifier of this transaction's back stack entry, if addToBackStack(String) had been called. Otherwise, returns a negative number. |
-
commitAllowingStateLoss
added in API level 11
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.Returns int
大致意思是說使用的 commit方法是在Activity的onSaveInstanceState()之后調用的,這樣會出錯,因為onSaveInstanceState
方法是在該Activity即將被銷毀前調用,來保存Activity數據的,如果在保存玩狀態后再給它添加Fragment就會出錯。解決辦法就
是把commit()方法替換成 commitAllowingStateLoss()就行了,其效果是一樣的。