Exception - java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

使用fragment的时候出现这个exception:

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManagerImpl.java:1377)

at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManagerImpl.java:1395)

是在使用FragmentTransaction,commit方法添加一个fragment出现的错误。

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

public abstract intcommitAllowingStateLoss()

Added inAPI level 11

Likecommit()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方法不可以在onSaveInstanceState 之后调用,因为onSaveInstanceState方法是activity在即将被销毁前调用,来保存activity状态,如果在保存完后再给它添加fragment就会出错。

解决方法:把commit方法换成commitAllowingStateLoss()即可,效果一样。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容