欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

解决DialogFragment调用show方法报错问题

程序员文章站 2022-07-15 12:25:10
...
在Android 3.0以后,Google官方推荐使用DialogFragment代替Dialog使用,但是这个有个bug,就是DialogFragment调用show方法会出现
Caused by: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState

这个恶心的错误,如何解决呢?

解决方案就是写一个基类继承DialogFragment

public class ResolveShowBugDialogFragment extends DialogFragment {

    @Override
    public void show(FragmentManager manager, String tag) {
        try {
            FragmentTransaction ft = manager.beginTransaction();
            ft.add(this, tag).addToBackStack(null);
            ft.commitAllowingStateLoss();
        } catch (IllegalStateException e) {
        }
    }

    boolean mIsStateAlreadySaved = false;
    boolean mPendingShowDialog = false;

    @Override
    public void onResume() {
        onResumeFragments();
        super.onResume();
    }

    public void onResumeFragments() {
        mIsStateAlreadySaved = false;
        if (mPendingShowDialog) {
            mPendingShowDialog = false;
            showSnoozeDialog();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        mIsStateAlreadySaved = true;
    }

    private void showSnoozeDialog() {
        if (mIsStateAlreadySaved) {
            mPendingShowDialog = true;
        } else {
            FragmentManager fm = getFragmentManager();
            ResolveShowBugDialogFragment snoozeDialog = new ResolveShowBugDialogFragment();
            snoozeDialog.show(fm, "BaseDialogFragment");
        }
    }
}
参考链接:https://*.com/questions/14262312/java-lang-illegalstateexception-can-not-perform-this-action-after-onsaveinstanc