解决Can not perform this action after onSaveInstanceState问题

最近用fragment报以下问题

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
	at android.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1332)
	at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1350)
	at android.app.BackStackRecord.commitInternal(BackStackRecord.java:597)
	at android.app.BackStackRecord.commit(BackStackRecord.java:575)
	at android.app.DialogFragment.show(DialogFragment.java:230)

是在使用FragmentTransition的 commit方法添加一个Fragment的时候出现的,后来在官网找到了相关的

说明:http://developer.android.com/reference/android/app/FragmentTransaction.html#commitAllowingStateLoss()


  /**
     * Like {@link #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.
     */
    public abstract int commitAllowingStateLoss();


大致意思是说我使用的 commit方法是在Activity的onSaveInstanceState()之后调用的,这样会出错,因为onSaveInstanceState

方法是在该Activity即将被销毁前调用,来保存Activity数据的,如果在保存玩状态后再给它添加Fragment就会出错。解决办法就

是把commit()方法替换成 commitAllowingStateLoss()就行了,其效果是一样的。


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章