为Dialog增加弹框优先级

原文:Android优雅实现弹窗优先级管理

看了一个增加弹框优先级的文字,自己写了一个自定义弹框,加了优先级,效果还是不错的

首先是自定义弹框MyBaseDialog(可导入布局,也有默认布局) , 实现的MyDialogInterface接口就是为了优先级的:

public class MyBaseDialog extends Dialog implements MyDialogInterface {

    private String title;
    private String content;
    /**
     * true  显示2个按钮
     * false 显示1个按钮
     */
    private boolean showTwoBtn;
    private String leftStr;
    private View.OnClickListener leftListener;
    private String rightStr;
    private View.OnClickListener rightListener;
    private boolean cancelable;
    private boolean canceledOnTouchOutside;
    /**
     * 是否使用自定义弹框
     * useUseDefineView = true,需要传入useDefineLayout
     */
    private boolean useUseDefineView;
    private View useDefineLayout;
    /**
     * 是否被挤出(每个实现DialogManager.Dialog的窗口类都需要新建该变量)
     */
    private boolean isCrowdOut;


    private MyBaseDialog(Context context, Builder builder) {
        super(context);

        useUseDefineView = builder.useUseDefineView;
        useDefineLayout = builder.useDefineLayout;

        cancelable = builder.cancelable;
        canceledOnTouchOutside = builder.canceledOnTouchOutside;

        if (useUseDefineView) {
            setContentView(useDefineLayout);
        } else {
            title = builder.title;
            content = builder.content;
            showTwoBtn = builder.showTwoBtn;
            leftStr = builder.leftStr;
            leftListener = builder.leftListener;
            rightStr = builder.rightStr;
            rightListener = builder.rightListener;

            View view = LayoutInflater.from(context).inflate(R.layout.dialog_my_base_dialog_layout, null);
            setContentView(view);
            TextView tvTitle = view.findViewById(R.id.tv_dialog_title);
            TextView tvContent = view.findViewById(R.id.tv_dialog_content);
            TextView tvLeftBtn = view.findViewById(R.id.tv_dialog_btn_left);
            View line = view.findViewById(R.id.view_dialog_btn_line);
            TextView tvRightBtn = view.findViewById(R.id.tv_dialog_btn_right);

            tvTitle.setText(title);
            tvContent.setText(content);
            tvLeftBtn.setText(leftStr);
            tvLeftBtn.setOnClickListener(leftListener);
            if (showTwoBtn) {
                line.setVisibility(View.VISIBLE);
                tvRightBtn.setVisibility(View.VISIBLE);
                tvRightBtn.setText(rightStr);
                tvRightBtn.setOnClickListener(rightListener);
            } else {
                line.setVisibility(View.GONE);
                tvRightBtn.setVisibility(View.GONE);
            }
        }

        setCancelable(cancelable);
        setCanceledOnTouchOutside(canceledOnTouchOutside);

        WindowManager.LayoutParams params = getWindow().getAttributes();
        //getMetricsWidth(context) 得到屏幕宽度
        params.width = Utils.getMetricsWidth(context) / 3 * 2;
        //设置dialog宽度,高度相同处理即可   需在dialog.show()或者setContentView(view)后设置方有效果
        getWindow().setAttributes(params);
        //设置背景  很重要   不设不行~~~
        GradientDrawable drawable = new GradientDrawable();
        drawable.setColor(Color.parseColor("#00000000"));
        getWindow().setBackgroundDrawable(drawable);

    }


    @Override
    public void dismiss(boolean isCrowdOut) {
        //isCrowdOut在super.dismiss()之前赋值
        this.isCrowdOut = isCrowdOut;
        super.dismiss();
    }

    @Override
    public void setOnDismissListener(final InterfaceManager.OnDismissListener listener) {
        setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                listener.onDismiss(isCrowdOut);
            }
        });
    }

    @Override
    public void setOnShowListener(final InterfaceManager.OnShowListener listener) {
        setOnShowListener(new OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                listener.onShow();
            }
        });
    }

    /**
     * 每个实现DialogManager.Dialog的窗口类都需要实现该方法,告诉DialogManager是否可展示此窗口
     * (比如有些窗口只在页面的某个tab下才能展示)
     */
    @Override
    public boolean isCanShow() {
        return true;
    }

    @Override
    public void show() {
        super.show();
    }

    public static class Builder {
        private MyBaseDialog dialog;
        private String title;
        private String content;
        private boolean showTwoBtn;
        private String leftStr;
        private View.OnClickListener leftListener;
        private String rightStr;
        private View.OnClickListener rightListener;
        private boolean cancelable = false;
        private boolean canceledOnTouchOutside = false;
        private boolean useUseDefineView = false;
        private View useDefineLayout;

        public MyBaseDialog getDialog() {
            return dialog;
        }

        /**
         * 需要使用自定义view时
         *
         * @param useUseDefineView true使用自定义view,默认为false
         * @param useDefineLayout  自定义view
         */
        public Builder setUseSimpleView(boolean useUseDefineView, View useDefineLayout) {
            this.useUseDefineView = useUseDefineView;
            this.useDefineLayout = useDefineLayout;
            return this;
        }

        public Builder setTitle(String title) {
            this.title = title;
            return this;
        }

        public Builder setContent(String content) {
            this.content = content;
            return this;
        }

        public Builder setOneBtn(String leftStr, View.OnClickListener leftListener) {
            this.showTwoBtn = false;
            this.leftStr = leftStr;
            this.leftListener = leftListener;
            return this;
        }

        public Builder setTwoBtn(String leftStr, View.OnClickListener leftListener, String rightStr, View.OnClickListener rightListener) {
            this.showTwoBtn = true;
            this.leftStr = leftStr;
            this.leftListener = leftListener;
            this.rightStr = rightStr;
            this.rightListener = rightListener;
            return this;
        }

        public Builder setCancelable(boolean cancelable) {
            this.cancelable = cancelable;
            return this;
        }

        public Builder setCanceledOnTouchOutside(boolean canceledOnTouchOutside) {
            this.canceledOnTouchOutside = canceledOnTouchOutside;
            return this;
        }

        public MyBaseDialog build(Context context) {
            dialog = new MyBaseDialog(context, this);
            return dialog;
        }
    }
}

这里开始都是弹框优先级相关的
InterfaceManager:

public class InterfaceManager {
    public interface MyDialogInterface {
        /**
         * 展示
         */
        void show();

        /**
         * 关闭
         *
         * @param isCrowdOut 是否被挤出
         */
        void dismiss(boolean isCrowdOut);

        /**
         * 设置“窗口”关闭监听
         */
        void setOnDismissListener(OnDismissListener listener);

        /**
         * 设置“窗口”展示监听
         */
        void setOnShowListener(OnShowListener listener);

        /**
         * 是否满足show的条件(如处于某个tab,不关心时返回true就行)
         */
        boolean isCanShow();
    }

    /**
     * “窗口”展示监听
     */
    public interface OnShowListener {
        void onShow();
    }

    /**
     * “窗口”关闭监听
     */
    public interface OnDismissListener {
        /**
         * @param isCrowdOut 是否被挤出
         */
        void onDismiss(boolean isCrowdOut);
    }
}

DialogParam:

public class DialogParam {
    /**
     * “窗口”
     */
    private MyBaseDialog dialog;
    /**
     * 优先级,值越大优先级越高
     */
    private int priority;
    /**
     * 当前是否处于show状态
     */
    private boolean isShowing;
    /**
     * 是否准备show(在show之后非用户自己手动关掉弹窗(调dismiss或触摸弹窗外部)
     * 接着show了一个优先级更高的Dialog,当该Dialog dismiss后可自动show剩下的
     * 优先级最高的Dialog
     * )
     */
    private boolean prepareShow;

    private DialogParam(Builder builder) {
        dialog = builder.dialog;
        priority = builder.priority;
        prepareShow = builder.prepareShow;
    }

    public MyBaseDialog getDialog() {
        return dialog;
    }

    public void setDialog(MyBaseDialog dialog) {
        this.dialog = dialog;
    }

    public int getPriority() {
        return priority;
    }

    public void setPriority(int priority) {
        this.priority = priority;
    }

    public boolean isShowing() {
        return isShowing;
    }

    public void setShowing(boolean showing) {
        isShowing = showing;
    }

    public boolean isPrepareShow() {
        return prepareShow;
    }

    public void setPrepareShow(boolean prepareShow) {
        this.prepareShow = prepareShow;
    }

    public static class Builder {
        /**
         * “窗口”
         */
        private MyBaseDialog dialog;
        /**
         * 优先级,值越大优先级越高
         */
        private int priority;
        /**
         * 是否准备show(在show之后非用户自己手动关掉弹窗(调dismiss或触摸弹窗外部)
         * 接着show了一个优先级更高的Dialog,当该Dialog dismiss后可自动show剩下的
         * 优先级最高的Dialog
         * )
         */
        private boolean prepareShow = true;

        public Builder dialog(MyBaseDialog dialog) {
            this.dialog = dialog;
            return this;
        }

        public Builder priority(int priority) {
            this.priority = priority;
            return this;
        }

        public Builder prepareShow(boolean prepareShow) {
            this.prepareShow = prepareShow;
            return this;
        }

        public DialogParam build() {
            return new DialogParam(this);
        }
    }
}

DialogManager:

public class DialogManager {
    private List<DialogParam> mDialogs;
    private static DialogManager instance;

    private DialogManager() {

    }

    /**
     * 获取弹窗管理者
     *
     * @return
     */
    public static DialogManager getInstance() {
        if (instance == null) {
            synchronized (DialogManager.class) {
                if (instance == null) {
                    instance = new DialogManager();
                }
            }
        }
        return instance;
    }

    /**
     * 添加弹窗
     *
     * @param dialogParam 待添加的弹窗
     */
    public synchronized void add(final DialogParam dialogParam) {
        if (dialogParam != null && dialogParam.getDialog() != null) {
            if (mDialogs == null) {
                mDialogs = new ArrayList<>();
            }
            dialogParam.getDialog().setOnShowListener(new OnShowListener() {
                @Override
                public void onShow() {
                    dialogParam.setShowing(true);
                    dialogParam.setPrepareShow(false);
                }
            });

            dialogParam.getDialog().setOnDismissListener(new OnDismissListener() {
                @Override
                public void onDismiss(boolean isCrowdOut) {
                    dialogParam.setShowing(false);
                    if (isCrowdOut) {
                        dialogParam.setPrepareShow(true);
                    } else {
                        mDialogs.remove(dialogParam);
                        showNext();
                    }
                }
            });
            mDialogs.add(dialogParam);
        }
    }

    /**
     * 展示弹窗
     *
     * @param dialogParam 待展示的弹窗
     */
    public synchronized void show(DialogParam dialogParam) {
        if (dialogParam != null && dialogParam.getDialog() != null) {
            if (mDialogs == null) {
                if (dialogParam.getDialog().isCanShow()) {
                    dialogParam.getDialog().show();
                }
            } else {
                /*判断优先级及是否可展示*/
                maybeShow(dialogParam);
            }
        }
    }

    /**
     * 展示弹窗(优先级最高的Dialog)
     */
    public synchronized void show() {
        DialogParam dialogParam = getMaxPriorityDialog();
        if (dialogParam != null) {
            MyBaseDialog dialog = dialogParam.getDialog();
            if (dialog != null && dialog.isCanShow()) {
                dialog.show();
            }
        }
    }

    /**
     * 清除弹窗管理者
     */
    public synchronized void clear() {
        if (mDialogs != null) {
            for (int i = 0, size = mDialogs.size(); i < size; i++) {
                if (mDialogs.get(i) != null) {
                    mDialogs.get(i).setPrepareShow(false);
                }
            }
            for (int i = 0, size = mDialogs.size(); i < size; i++) {
                if (mDialogs.get(i) != null) {
                    MyBaseDialog dialog = mDialogs.get(i).getDialog();
                    if (dialog != null) {
                        dialog.dismiss(false);
                    }
                }
            }
            mDialogs.clear();
        }
    }

    /**
     * 清除弹窗管理者
     *
     * @param dismiss 是否同时dismiss掉弹窗管理者维护的弹窗
     */
    public synchronized void clear(boolean dismiss) {
        if (mDialogs != null) {
            for (int i = 0, size = mDialogs.size(); i < size; i++) {
                if (mDialogs.get(i) != null) {
                    mDialogs.get(i).setPrepareShow(false);
                }
            }
            if (dismiss) {
                for (int i = 0, size = mDialogs.size(); i < size; i++) {
                    if (mDialogs.get(i) != null) {
                        MyBaseDialog dialog = mDialogs.get(i).getDialog();
                        if (dialog != null) {
                            dialog.dismiss(false);
                        }
                    }
                }
            }
            mDialogs.clear();
        }
    }

    /**
     * 展示下一个优先级最大的Dialog(非自行调用dismiss而是被优先级高的弹窗show后挤掉)
     */
    private synchronized void showNext() {
        DialogParam dialog = getMaxPriorityDialog();
        if (dialog != null) {
            if (dialog.isPrepareShow() && dialog.getDialog().isCanShow()) {
                dialog.getDialog().show();
            }
        }

    }

    /**
     * 展示弹窗(满足条件可展示)
     *
     * @param dialogParam 待展示的弹窗
     */
    private void maybeShow(DialogParam dialogParam) {
        if (dialogParam != null && dialogParam.getDialog() != null) {
            DialogParam topShowDialog = getShowingDialog();
            if (topShowDialog == null) {
                if (dialogParam.getDialog().isCanShow()) {
                    dialogParam.getDialog().show();
                }
            } else {
                /*获取优先级*/
                int priority = dialogParam.getPriority();
                if (priority >= topShowDialog.getPriority()) {
                    if (dialogParam.getDialog().isCanShow()) {
                        dialogParam.getDialog().show();
                        topShowDialog.getDialog().dismiss(true);
                        /*设置参数支持当前show关闭后自动show带该参数的优先级最高的弹窗*/
                        topShowDialog.setPrepareShow(true);
                    }
                }
            }
        }
    }

    /**
     * 获取当前栈中优先级最高的Dialog(优先级相同则返回后添加的弹窗)
     */
    private synchronized DialogParam getMaxPriorityDialog() {
        if (mDialogs != null) {
            int maxPriority = -1;
            int position = -1;
            for (int i = 0, size = mDialogs.size(); i < size; i++) {
                DialogParam dialog = mDialogs.get(i);
                if (i == 0) {
                    position = 0;
                    maxPriority = dialog.getPriority();
                } else {
                    if (dialog.getPriority() >= maxPriority) {
                        position = i;
                        maxPriority = dialog.getPriority();
                    }
                }
            }
            if (position != -1) {
                return mDialogs.get(position);
            } else {
                return null;
            }
        }
        return null;
    }

    /**
     * 获取当前处于show状态的弹窗
     */
    private synchronized DialogParam getShowingDialog() {
        if (mDialogs != null) {
            for (int i = 0, size = mDialogs.size(); i < size; i++) {
                DialogParam dialogParam = mDialogs.get(i);
                if (dialogParam != null && dialogParam.getDialog() != null && dialogParam.isShowing()) {
                    return dialogParam;
                }
            }
        }
        return null;
    }
}

最后调用的时候增加优先级,调用DialogParam里的show()方法来显示弹框

 final MyBaseDialog.Builder myDialog1 = new MyBaseDialog.Builder();
        myDialog1.setTitle("我是111标题")
                .setContent("我是内容我是内容我是内容")
                .setTwoBtn("1左边", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        myDialog1.getDialog().dismiss(false);
                    }
                }, "1右边", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        myDialog1.getDialog().dismiss(false);
                    }
                })
                .build(MainActivity.this);

        final MyBaseDialog.Builder myDialog2 = new MyBaseDialog.Builder();
        myDialog2.setTitle("我是2222标题")
                .setContent("asfsdg水电费那可是当你asfsdg水电费那可是当你asfsdg水电费那可是当你")
                .setCancelable(true)
                .setCanceledOnTouchOutside(true)
                .setOneBtn("2按钮", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        myDialog2.getDialog().dismiss(false);
                    }
                })
                .build(MainActivity.this);

        final MyBaseDialog.Builder myDialog3 = new MyBaseDialog.Builder();
        myDialog3.setTitle("我是3333标题")
                .setContent("搜到附近束带结发搜到附近束带结发搜到附近束带结发搜到附近束带结发搜到附近束带结发搜到附近束带结发搜到附近束带结发")
                .setOneBtn("3按钮", new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        myDialog3.getDialog().dismiss(false);
                    }
                })
                .build(MainActivity.this);

        View view = LayoutInflater.from(this).inflate(R.layout.dialog_my_view, null);
        final MyBaseDialog.Builder myDialog4 = new MyBaseDialog.Builder();
        myDialog4.setUseSimpleView(true, view)
                .build(this);
        TextView tv = view.findViewById(R.id.tv_dialog_my_view);
        tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toastShort("dianle");
                myDialog4.getDialog().dismiss(false);
            }
        });

        DialogManager.getInstance().add(new DialogParam.Builder().dialog(myDialog1.getDialog()).priority(3).build());
        DialogManager.getInstance().add(new DialogParam.Builder().dialog(myDialog2.getDialog()).priority(1).build());
        DialogManager.getInstance().add(new DialogParam.Builder().dialog(myDialog3.getDialog()).priority(2).build());
        DialogManager.getInstance().add(new DialogParam.Builder().dialog(myDialog4.getDialog()).priority(5).build());

        DialogManager.getInstance().show();