DialogFragment show() IllegalStateException

使用DialogFragment的show方法会发生IllegalStateException异常,解决问题的方案是重写show方法。API源码中的show方法实际调用的是FragmentTransaction的commit()方法,我们通过重写的方式将其改用commitAllowingStateLoss就可以了。

public abstract class BaseDialogFragment extends DialogFragment {
    private static final String TAG = "BaseDialogFragment";

    public void show(FragmentManager fm, String TAG) {
        /* // 源码代码
        mDismissed = false;
        mShownByMe = true;
        FragmentTransaction ft = manager.beginTransaction();
        ft.add(this, tag);
        ft.commit();
        */

        Class clz = this.getClass();

        try {
            Field mDismissed = clz.getDeclaredField("mDismissed");
            mDismissed.setAccessible(true);
            mDismissed.set(this, false);
        } catch (NoSuchFieldException e) {
            Log.e(TAG, e.toString());
        } catch (IllegalAccessException e) {
            Log.e(TAG, e.toString());
        }
        try {
            Field mShownByMe = clz.getDeclaredField("mShownByMe");
            mShownByMe.setAccessible(true);
            mShownByMe.set(this, true);
        } catch (NoSuchFieldException e) {
            Log.e(TAG, e.toString());
        } catch (IllegalAccessException e) {
            Log.e(TAG, e.toString());
        }

        FragmentTransaction ft = fm.beginTransaction();
        ft.add(this, TAG);
        ft.commitAllowingStateLoss();
    }
}

那么commit()方法和commitAllowingStateLoss()方法,他们之间有啥区别?详见commit & commitAllowingStateLoss

你可能感兴趣的:(DialogFragment show() IllegalStateException)