logcat: Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
注:onSaveInstanceState的調(diào)用遵循一個重要原則关贵,即當(dāng)系統(tǒng)“未經(jīng)你許可”時銷毀了你的activity怒详,則onSaveInstanceState會被系統(tǒng)調(diào)用,這是系統(tǒng)的責(zé)任秩命,因為它必須要提供一個機(jī)會讓你保存你的數(shù)據(jù)军俊。
Fragment還有ActivityGroup侥加,在調(diào)用saveInstanceState存在Bug,可能是google對saveInstanceState的實現(xiàn)做過修改
粪躬。是在使用FragmentTransition的 commit方法添加一個Fragment的時候出現(xiàn)的担败,后來在官網(wǎng)找到了相關(guān)的說明:
http://developer.android.com/reference/android/app/FragmentTransaction.html#commitAllowingStateLoss()
public abstract int commitAllowingStateLoss ()
Added in API level 11. 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.
大致意思是說我使用的 commit方法是在Activity的onSaveInstanceState()之后調(diào)用的,這樣會出錯镰官,因為onSaveInstanceState方法是在該Activity即將被銷毀前調(diào)用提前,來保存Activity數(shù)據(jù)的,如果在保存玩狀態(tài)后再給它添加Fragment就會出錯泳唠。
解決辦法
- 就是把commit()方法替換成 commitAllowingStateLoss()就行了
- Activity的onSaveInstanceState方法中不再執(zhí)行super.onSaveInstanceState().缺點就是會丟失部分信息,導(dǎo)致重新返回此Activity時出現(xiàn)問題.但是目前在本應(yīng)用中無礙