这个问题可以看作是ft.commit()和ft.commitAllowingStateLoss()的区别,在Activity的onSaveInstanceState()方法之后再commit会抛出异常。看源码:commit()内部实现这个方法

会先判断事务是否被提交过,再提交会报异常,所以每次都是开启一个新事务;最后调FragmentManager的enqueueAction方法里的checkStateLoss()方法:

如果Activity调用过onSaveInstanceState()或者onStop()则isStateSaved()方法返回true,这时就会抛出异常。
解决办法:使用dismissAllowingStateLoss()方法替换,因为dismissAllowingStateLoss中调用的是commitAllowingStateLoss()方法,此方法内的enqueueAction方法入参allowStateLoss为true,跳过checkStateLoss()方法,不会抛出异常。
网友评论