Fragment 无法在Activity.onSaveInsta

2017-11-24  本文已影响0人  jiangjh

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

注:onSaveInstanceState的调用遵循一个重要原则,即当系统“未经你许可”时销毁了你的activity,则onSaveInstanceState会被系统调用,这是系统的责任,因为它必须要提供一个机会让你保存你的数据。

Fragment还有ActivityGroup,在调用saveInstanceState存在Bug,可能是google对saveInstanceState的实现做过修改。是在使用FragmentTransition的 commit方法添加一个Fragment的时候出现的,后来在官网找到了相关的说明:
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()之后调用的,这样会出错,因为onSaveInstanceState方法是在该Activity即将被销毁前调用,来保存Activity数据的,如果在保存玩状态后再给它添加Fragment就会出错。

解决办法

  1. 就是把commit()方法替换成 commitAllowingStateLoss()就行了
  2. Activity的onSaveInstanceState方法中不再执行super.onSaveInstanceState().缺点就是会丢失部分信息,导致重新返回此Activity时出现问题.但是目前在本应用中无碍
上一篇下一篇

猜你喜欢

热点阅读