DialogFragment细枝末节

2019-03-10  本文已影响0人  迷人的萨克斯

[图片上传失败...(image-2f551a-1552206999736)]

前言

在Android中,创建对话框有两种,一种是Dialog,另外一种则是今天的主题,官方推荐的DialogFragmet,关于Dialog的使用就不赘述了,今天主要介绍DialogFragment的使用以及一些需要注意的事项,主要有以下几点。

一、DialogFragment的优势

二、DialogFragment的使用

1.方式一具体使用

    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Logger.d(TAG, "onCreateDialog");
        AppCompatDialog appCompatDialog = new AppCompatDialog(requireActivity());
        TextView textView = new TextView(requireActivity());
        textView.setText("通过onCreateDialog使用DialogFragment");
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 28);
        appCompatDialog.setContentView(textView);
        return appCompatDialog;
    }
    private void showOnCreateDialogFragment(){
        DialogFragment dialogFragment = new DialogFragment();
        dialogFragment.show(getSupportFragmentManager(), "tag");
    }

2.方式二具体使用

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Logger.d(TAG, "onCreateView");
        TextView textView = new TextView(requireActivity());
        textView.setText("通过onCreateView使用DialogFragment");
        textView.setGravity(Gravity.CENTER);
        textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 28);
        return textView;
    }

3.DialogFragment中对Dialog属性的设置,我们可以在DialogFragment的onStar中来对Dialog的样式进行设置,有一点需要注意的是,对于Dialog样式的设置,必须在onCretaeDialog方法后面执行,不然得不到Dialog实例,我们可以打印一下DialogFragment从创建到show出来时执行的具体生命周期方法,具体内容如下:

2019-03-10 14:19:10.971 22626-22626/org.lym.sourcecodeparse D/DialogFragment: onAttach
2019-03-10 14:19:10.971 22626-22626/org.lym.sourcecodeparse D/DialogFragment: onCreate
2019-03-10 14:19:10.972 22626-22626/org.lym.sourcecodeparse D/DialogFragment: onCreateDialog
2019-03-10 14:19:10.994 22626-22626/org.lym.sourcecodeparse D/DialogFragment: onActivityCreated
2019-03-10 14:19:11.186 22626-22626/org.lym.sourcecodeparse D/DialogFragment: onStart
2019-03-10 14:19:11.186 22626-22626/org.lym.sourcecodeparse D/DialogFragment: onResume
    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        Window window = dialog.getWindow();
        if (window == null) {
            return;
        }
        WindowManager.LayoutParams attributes = window.getAttributes();
        //设置Dialog窗口的高度
        attributes.height = WindowManager.LayoutParams.MATCH_PARENT;
        //设置Dialog窗口的宽度
        attributes.width = WindowManager.LayoutParams.MATCH_PARENT;
        //设置Dialog的居中方向
        attributes.gravity = Gravity.CENTER;
        //设置Dialog弹出时背景的透明度
        attributes.dimAmount = 0.6f;
        //设置Dialog水平方向的间距
        attributes.horizontalMargin = 0f;
        //设置Dialog垂直方向的间距
        attributes.verticalMargin = 0f;
        //设置Dialog显示时X轴的坐标,具体屏幕X轴的偏移量
        attributes.x = 0;
        //设置Dialog显示时Y轴的坐标,距离屏幕Y轴的偏移量
        attributes.y = 0;
        //设置Dialog的透明度
        attributes.alpha = 0f;
        //设置Dialog显示和消失时的动画
        attributes.windowAnimations = 0;
        window.setAttributes(attributes);
        Logger.d(TAG, "onStart");
    }

三、DialogFragmeng源码分析

1.下面先贴一下DialogFragment的部分源码,并进行简要分析。

public class DialogFragment extends Fragment implements OnCancelListener, OnDismissListener {
    boolean mViewDestroyed;
    boolean mDismissed;
    boolean mShownByMe;

    public DialogFragment() {
    }
    
    //标准的显示Fragment的方法,没什么好说的
    public void show(FragmentManager manager, String tag) {
        this.mDismissed = false;
        this.mShownByMe = true;
        FragmentTransaction ft = manager.beginTransaction();
        ft.add(this, tag);
        ft.commit();
    }
    
    //传入一个事务管理,将fragment加入到事务管理中,并返回回退栈id
    //返回的mBackStackId将在下文中用到
    public int show(FragmentTransaction transaction, String tag) {
        this.mDismissed = false;
        this.mShownByMe = true;
        transaction.add(this, tag);
        this.mViewDestroyed = false;
        this.mBackStackId = transaction.commit();
        return this.mBackStackId;
    }
    
    //第一个show方法的加强版,看名字就知道,使用这个方法之后,则会立即执行fragment当中相关的方法,这个待会儿作出解释
    public void showNow(FragmentManager manager, String tag) {
        this.mDismissed = false;
        this.mShownByMe = true;
        FragmentTransaction ft = manager.beginTransaction();
        ft.add(this, tag);
        ft.commitNow();
    }

    //Dialaog消失时的回调,setOndismissListener是在onActivityCreate中设置的,当前正是把dialog给dismiss,并没有让dialogfragment出栈
    public void dismiss() {
        this.dismissInternal(false);
    }
    
    //dismiss的加强版,先消失dialog,并将dialogfragment移除栈内
    public void dismissAllowingStateLoss() {
        this.dismissInternal(true);
    }

    //显示判断dialog,是否已经消失,如果已经消失,则不做任何操作
    //1.如果dialog实例不为空,先调用dialog的dismiss方法,隐藏dialog
    //2.如果先前调用的是public int show(FragmentTransaction transaction, String tag)
    //方法显示的dialogfragment,那么此时会根据之前返回的mBackStackId来将fragment移除栈内
    //3.如果不是则再启用事务将dialogfragment移除栈内,这里会根据传入的allowStateLoss来区分
    //提交事务的方法
    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();
                }
            }

        }
    }
    
    //如果子类重写该方法,那么使用的就是你自定义的dialog
    @NonNull
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        return new Dialog(this.getActivity(), this.getTheme());
    }
    
    //dialog设置了onDismissListener后的回调,如果dialog正常消失,次回调中的方法不会调用到
    //因为在DialogFragment的onStar方法中将mViewDestroyed变量赋值为true,dialog显示设置到调用显示出来的生命周期回调我们已经打印过了。
    public void onDismiss(DialogInterface dialog) {
        if (!this.mViewDestroyed) {
            this.dismissInternal(true);
        }
    }

    //该方法,先判断Dialog是否已经显示,然后会取onCreateView中返回的View,如果View不为空,那么该View将作为Dialog的内容布局,所以,如果你同时重写了onCreateDialog和onCreateView方法,那么会优先采用onCreateView当中的View作为内容布局,然后再作了一些监听设置
    //设置了dialog是否可点击
    //设置了dialog的消失监听onDismissListener,所以消失时会回调文中的dimiss方法
    //设置了dialog的取消监听onCancelListener,在取消时会回调文中的onCancel方法
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (this.mShowsDialog) {
            View view = this.getView();
            if (view != null) {
                if (view.getParent() != null) {
                    throw new IllegalStateException("DialogFragment can not be attached to a container view");
                }

                this.mDialog.setContentView(view);
            }

            Activity activity = this.getActivity();
            if (activity != null) {
                this.mDialog.setOwnerActivity(activity);
            }

            this.mDialog.setCancelable(this.mCancelable);
            this.mDialog.setOnCancelListener(this);
            this.mDialog.setOnDismissListener(this);
            if (savedInstanceState != null) {
                Bundle dialogState = savedInstanceState.getBundle("android:savedDialogState");
                if (dialogState != null) {
                    this.mDialog.onRestoreInstanceState(dialogState);
                }
            }

        }
    }
}

2.源码分析总结

四、细节注意事项

    Process: org.lym.sourcecodeparse, PID: 27108
    java.lang.IllegalStateException: Fragment already added: DialogFragment{8262d74 #0 tag}
        at android.support.v4.app.FragmentManagerImpl.addFragment(FragmentManager.java:1893)
        at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:760)
        at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2595)
        at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2382)
        at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2337)
//mListener为提供到外部使用的回调
 @Override
    public void onDismiss(DialogInterface dialog) {
        super.onDismiss(dialog);
        mListener.onDismiss(dialog);
        Logger.d(TAG, "onDismiss");
    }
    
    //复写setOnDismissListener必须发生在父类的onActivityCreate之后
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getDialog() != null && null != mListener) {
            getDialog().setOnDismissListener(new DialogInterface.OnDismissListener() {
                @Override
                public void onDismiss(DialogInterface dialog) {
                    ToastUtils.showToast("覆盖后的OnDismiss Listener");
                }
            });
        }
        Logger.d(TAG, "onActivityCreated");
    }

结语:以上便是全文的内容,是自己在使用DialogFragment中碰到了一些坑以及学习后的一些理解,希望能对您有帮助。

上一篇 下一篇

猜你喜欢

热点阅读