标签:
============2
今天使用Fragment的时候,出现了这个错误 IllegalStateException: Can not perform this action after onSaveInstanceState:
是在使用FragmentTransition的 commit方法添加一个Fragment的时候出现的,后来在官网找到了相关的
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就会出错。解决办法就
是把commit()方法替换成 commitAllowingStateLoss()就行了,其效果是一样的。
========1
当快速双击调用FragmentTransaction.add()方法添加fragmentA,而fragmentA不是每次单独生成的,就会引起这个异常。
DialogFragment.show()内部调用了FragmentTransaction.add()方法,所以调用DialogFragment.show()方法时候也可能会出现这个异常。
在add()方法时候,先判断fragmentA.isAdded(),如下调用可以避免该异常:
if(!fragmentA.isAdded()){
FragmentManager manager = ((FragmentActivity)context).getSupportFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.add(fragmentA, "fragment_name");
ft.commit();
}
标签:
原文地址:http://www.cnblogs.com/awkflf11/p/5164964.html