Fragment的commit方法和commitAllowingStateLoss方法的区别

来源:互联网 发布:淘宝店快递发货流程 编辑:程序博客网 时间:2024/06/06 00:42

几天用fragment的时候出现了一个bug,程序直接crash掉,抛出"can not perform this action after onSaveInstanceState" 异常,原来是FragmentTransaction的commit方法抛出的,最后将commit方法改为commitAllowingStateLoss方法,解决了问题。

那么这两个方法有什么区别呢?查看源码得知,commit和commitAllowingStateLoss方法最终都调用了BackStackRecord类的commitInternal(boolean allowStateLoss)方法,allowStateLoss:是否允许fragment的状态丢失,commit传的是false,commitAllowingStateLoss传的是true(即允许fragment的状态丢失),如果使用commit方法,系统会调用checkStateLoss()方法检查状态,如果已经保存就会抛出以下异常:

private void checkStateLoss() {    if (mStateSaved) {        throw new IllegalStateException(                "Can not perform this action after onSaveInstanceState");    }






1 0
原创粉丝点击