使用DialogFragment时出现的问题

最近公司项目里面有一些弹出的页面,采用了DialogFragment的方式,但是经常在调用Dismiss的时候会报错
Can not perform this action after onSaveInstanceState
网上找了很多都是说把commit()方法替换成 commitAllowingStateLoss()
还有说用反射重写show()方法,目的也是为了把show()方法中的commit()方法替换成 commitAllowingStateLoss()
具体如下:
@Override
public void show(FragmentManager manager, String tag) {
// super.show(manager, tag);
try {
Class c = Class.forName("android.support.v4.app.DialogFragment");
Constructor con = c.getConstructor();
Object obj = con.newInstance();
Field dismissed = c.getDeclaredField("mDismissed");
dismissed.setAccessible(true);
dismissed.set(obj, false);
Field shownByMe = c.getDeclaredField("mShownByMe");
shownByMe.setAccessible(true);
shownByMe.set(obj, false);
} catch (Exception e) {
e.printStackTrace();
}
FragmentTransaction ft = manager.beginTransaction();
ft.add(this, tag);
ft.commitAllowingStateLoss();
}

但是还是不行,这时候我发现弄错了问题所在,这里是在dissmiss()时报错的,我改show()方法有啥用。
然后翻看dissmiss()的源码发现,它其实调用的是this.dismissInternal(false);
void dismissInternal(boolean allowStateLoss) {
if (!this.mDismissed) {
this.mDismissed = true;
this.mShownByMe = false;
if (this.mDialog != null) {
this.mDialog.dismiss();
}

        this.mViewDestroyed = true;
        if (this.mBackStackId >= 0) {
            this.getFragmentManager().popBackStack(this.mBackStackId, 1);
            this.mBackStackId = -1;
        } else {
            FragmentTransaction ft = this.getFragmentManager().beginTransaction();
            ft.remove(this);
            if (allowStateLoss) {
                ft.commitAllowingStateLoss();
            } else {
                ft.commit();
            }
        }

    }
}

在这里看到了熟悉的commitAllowingStateLoss()和commit(),是通过allowStateLoss来判断调用哪个,很显然,问题的关键就再allowStateLoss这个参数。
然后又找到了领一个方法dismissAllowingStateLoss(),把用到dissmiss的地方,换成它就好了

你可能感兴趣的:(使用DialogFragment时出现的问题)