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();
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。