java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

最近在使用DialogFragment的时候偶尔遇到了这么一个异常:

java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

原因可能是Activity页面可能被回收了,系统调用了onSaveInstanceState,而这是刚好需要DialogFragment.show();

看了方法show()里面的源码

public voidshow(FragmentManager manager,String tag) {
    mDismissed=false;
    mShownByMe=true;
    FragmentTransaction ft = manager.beginTransaction();
    ft.add(this,tag);
    ft.commit();
}

最后调用的是commit()而不是commitAllowingStateLoss(),所以解决方法是不采用系统默认的show方法,而是用 FragmentTransaction控制,如下:

FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
Fragment prev = getSupportFragmentManager().findFragmentByTag("RepeatDialogFragment");
if(prev !=null) {
ft.remove(prev);
}
ft.addToBackStack(null);
// Create and show the dialog.
mRepeatDialogFragment= RepeatDialogFragment.newInstance(mRepeatList,mIsCustomRepeat);
ft.add(mRepeatDialogFragment,"RepeatDialogFragment");
ft.commitAllowingStateLoss();

你可能感兴趣的:(java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState)