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

在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://stackoverflow.com/questions/14262312/java-lang-illegalstateexception-can-not-perform-this-action-after-onsaveinstanc

你可能感兴趣的:(Android开发)