fragment 基本上是每个项目都会用到,一般我们会这么写:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragment_container, new MyFragment())
.commit();
但是有时候会报如下错误信息:
Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
意思就是说我们不能在调用onSaveInstanceState
进行commit
操作。网上的解决办法是使用commitAllowingStateLoss
替换commit
。确实是不报错了,但是为什么呢?commit
是会对状态进行检测,并抛出异常;而commitAllowingStateLoss
方法只是不进行状态检测,因此不会抛出异常。这明显是有点逃避问题,那么这个状态是什么判断而得出的呢?
在Activity
和FragmentActivity
内的onSaveInstanceState
方法保存了fragment
的状态。在onSaveInstanceState
方法后调用commit
和commitAllowingStateLoss
会引起一种问题:因内存不足而把不显示在前台的 activity (带有 fragment)销毁,之后用户再回到此 activity 页面时,是会丢失在onSaveInstanceState
后调用commit
方法提交的页面状态信息!
不同的只是调用commit
会报错,调用commitAllowingStateLoss
不报错(睁一只眼闭一只眼)。
谷歌在commitAllowingStateLoss
方法的注释上也写明,调用此方法会有丢失页面状态信息的风险。
- 一般情况下,尽量提早调用 commit 方法,比如说
onCreate()
; - 异步回调中避免使用
commit
; - 不得已的情况,可以使用
commitAllowingStateLoss
替代commit
。毕竟报错奔溃,比页面状态信息丢失更严重;
作者:chenxuxu
链接:
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。