Android java.lang.IllegalStateException: Fragment already added异常的处理
当快速双击调用FragmentTransaction.add()方法添加fragmentA,而fragmentA不是每次单独生成的,就会引起这个异常。
DialogFragment.show()内部调用了FragmentTransaction.add()方法,所以调用DialogFragment.show()方法时候也可能会出现这个异常。
/**
* Activity 中Fragment之间的切换
*/
private Fragment currentFragment;//主界面中当前显示的Fragment
fm = getSupportFragmentManager();
R.id.cotentID Activity中FrameLayout切换显示Fragment
public void SmartShow(Fragment showFrgment) {
FragmentTransaction ft = fm.beginTransaction();
String showName = showFrgment.getClass().getSimpleName();
Fragment sfrgment = fm.findFragmentByTag(showName);
if (currentFragment != null) {
ft.hide(currentFragment);
}
if (sfrgment == null&&!showFrgment.isAdded()) {
ft.add(R.id.cotentID, showFrgment, showName);
} else {
ft.show(sfrgment);
}
ft.commitAllowingStateLoss();
currentFragment = sfrgment;
}