安卓自定义Dialog之BaseDialog

来源:互联网 发布:千语淘客软件下载 编辑:程序博客网 时间:2024/05/21 12:08

项目里用到的dialog越来越多,样式也各式各样,为了方便,所以就考虑写一个BaseDialog。

新建BaseDialog继承Dialog

    public class BaseDialog extends Dialog {        public BaseDialog(Context context) {            super(context);        }        public BaseDialog(Context context, int themeResId) {            super(context, themeResId);        }        protected BaseDialog(Context context, boolean cancelable, OnCancelListener cancelListener) {            super(context, cancelable, cancelListener);        }    }
我们也仿造dialog的来设计,利用Builder模式静态成员类(嵌套类)
    public static class Builder {        private Context context;        private boolean cancelable = false;        private OnCancelListener cancelListener;        private int theme = R.style.commonDialog;        private CharSequence positionText;        private CharSequence negativeText;        private OnClickListener positiveListener;        private OnClickListener negativeListener;        private View centerView;        private CharSequence title;        private LayoutParams centerLP = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);        private Map<String, View> viewMap;}         public Builder(Context context) {            this.context = context;            viewMap = new HashMap<String, View>();        }        public Context getContext() {            return context;        }        public Builder setCancelable(boolean cancelable) {            this.cancelable = cancelable;            return this;        }        public Builder setCancelListener(OnCancelListener cancelListener) {            this.cancelListener = cancelListener;            return this;        }        public Builder setTheme(int theme) {            this.theme = theme;            return this;        }        public Builder setTitle(CharSequence title) {            this.title = title;            return this;        }        public Builder setTitle(int textId) {            this.title = getContext().getString(textId);            return this;        }        public Builder setCenterView(View centerView) {            this.centerView = centerView;            return this;        }        public Builder setCenterView(int resId) {            this.centerView = View.inflate(getContext(), resId, null);            return this;        }        public Builder setPositiveButton(int textId, OnClickListener listener) {            this.positionText = getContext().getString(textId);            this.positiveListener = listener;            return this;        }        public Builder setPositiveButton(CharSequence text, OnClickListener listener) {            this.positionText = text;            this.positiveListener = listener;            return this;        }        public Builder setNegativeButton(int textId, OnClickListener listener) {            this.negativeText = getContext().getString(textId);            ;            this.negativeListener = listener;            return this;        }        public Builder setNegativeButton(CharSequence text, OnClickListener listener) {            this.negativeText = text;            this.negativeListener = listener;            return this;        }

R.layout.common_base_dialog
长这样
这里写图片描述

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:background="@drawable/common_shape_dialog_round_white"    android:divider="@drawable/common_divider_pale"    android:orientation="vertical"    android:showDividers="middle" >    <LinearLayout        android:id="@+id/lay_title"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:gravity="center_vertical"        android:orientation="horizontal" >        <TextView            android:id="@+id/tv_title"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="1"            android:padding="10dp"            android:text=""            android:textColor="#333333"            android:textSize="16sp" />        <ImageView            android:id="@+id/iv_cancel"            android:layout_width="wrap_content"            android:layout_height="match_parent"            android:background="@drawable/common_selector_default"            android:paddingLeft="10dp"            android:paddingRight="10dp"            android:src="@mipmap/common_dialog_icon_cancel"/>    </LinearLayout>    <LinearLayout        android:id="@+id/lay_center"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="vertical" >    </LinearLayout>    <LinearLayout        android:id="@+id/lay_bottom"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:divider="@drawable/common_divider_pale"        android:gravity="center_horizontal"        android:orientation="horizontal"        android:showDividers="middle"        android:visibility="gone"        android:weightSum="2" >        <Button            android:id="@+id/btn_negative"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="1"            android:text="取消"            android:textColor="#333333"            android:textSize="14sp"            android:visibility="gone" />        <Button            android:id="@+id/btn_positive"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="1"            android:text="确定"            android:textColor="@color/white"            android:textSize="14sp"            android:visibility="gone" />    </LinearLayout></LinearLayout>

对外的create方法

    public Dialog create() {        final Dialog dialog = new Dialog(getContext(), theme);        dialog.setCancelable(cancelable);        dialog.setOnCancelListener(cancelListener);        View view = View.inflate(getContext(), R.layout.common_base_dialog, null);        dialog.setContentView(view);        TextView tv_title = (TextView) view.findViewById(R.id.tv_title);        if (!TextUtils.isEmpty(title)) {            tv_title.setText(title);        }        ImageView iv_cancel = (ImageView) view.findViewById(R.id.iv_cancel);        if (cancelable) {            iv_cancel.setVisibility(View.VISIBLE);            iv_cancel.setOnClickListener(new View.OnClickListener() {                @Override                public void onClick(View v) {                    dialog.cancel();                    if (cancelListener != null) {                        cancelListener.onCancel(dialog);                    }                }            });        } else {            iv_cancel.setVisibility(View.GONE);        }        if (TextUtils.isEmpty(positionText) && TextUtils.isEmpty(negativeText)) {                view.findViewById(R.id.lay_bottom).setVisibility(View.GONE);            } else {                View bottomView = view.findViewById(R.id.lay_bottom);                bottomView.setVisibility(View.VISIBLE);                Button btn_positive = (Button) bottomView.findViewById(R.id.btn_positive);                Button btn_negative = (Button) bottomView.findViewById(R.id.btn_negative);                if (TextUtils.isEmpty(positionText)) {                    btn_positive.setVisibility(View.GONE);                } else {                    btn_positive.setVisibility(View.VISIBLE);                    btn_positive.setText(positionText);                    btn_positive.setOnClickListener(new View.OnClickListener() {                        @Override                        public void onClick(View v) {                            dialog.dismiss();                            if (positiveListener != null) {                                positiveListener.onClick(dialog, BUTTON_POSITIVE);                            }                        }                    });                }                if (TextUtils.isEmpty(negativeText)) {                    btn_negative.setVisibility(View.GONE);                } else {                    btn_negative.setVisibility(View.VISIBLE);                    btn_negative.setText(negativeText);                    btn_negative.setOnClickListener(new View.OnClickListener() {                        @Override                        public void onClick(View v) {                            dialog.dismiss();                            if (negativeListener != null) {                                negativeListener.onClick(dialog, BUTTON_NEGATIVE);                            }                        }                    });                }                if (!TextUtils.isEmpty(positionText) && !TextUtils.isEmpty(negativeText)) {                    btn_negative.setBackgroundResource(R.drawable.common_selector_dialog_press_white);                    btn_positive.setBackgroundResource(R.drawable.common_selector_dialog_press_blue);                }            }            ViewGroup centerLay = (ViewGroup) view.findViewById(R.id.lay_center);            centerView = getCenterView(centerView, centerLay);            if (centerView != null) {                centerView.setLayoutParams(centerLP);                centerLay.addView(centerView);            }            initDialogSize(dialog);            return dialog;    }    private void initDialogSize(Dialog dialog) {        DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();        android.view.WindowManager.LayoutParams params = dialog.getWindow().getAttributes();        params.width = (int) (metrics.widthPixels - 10 * 2 * metrics.density);        params.height = android.view.WindowManager.LayoutParams.WRAP_CONTENT;    }    protected View getCenterView(View centerView, ViewGroup container) {        return centerView;    }

好了,BaseDialog的代码就这么多
在activity使用

public class DialogActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_dialog);    }    public Dialog connectDeviceWarn(final Context context, final DialogInterface.OnClickListener onClickListener) {        return normal(context, "标题", "要提示的msg", "确定按钮的text", "取消按钮的text", onClickListener);    }    public Dialog normal(final Context context, String title, String msg, String okText,                                String cancelText, final DialogInterface.OnClickListener onClickListener) {        BaseDialog.Builder builder = new BaseDialog.Builder(context) {            @Override            protected View getCenterView(View centerView, ViewGroup container) {                return centerView;            }        };        View view = View.inflate(context, R.layout.common_warn_dialog, null);        ((TextView) view.findViewById(R.id.dialog_hint)).setText(msg);        builder.setCenterView(view);        if (!TextUtils.isEmpty(okText)) {            builder.setPositiveButton(okText, onClickListener);        }        builder.setNegativeButton(cancelText, null);        builder.setTitle(title);        return builder.create();    }    public void baseDialog(View view){        connectDeviceWarn(DialogActivity.this, new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {                //            }        }).show();    }}

实际使用时可以把一种dialog写成一个工具类,那就可以随便使用了,如下

public class WarnDialog {    /**     * 确认提交警告     **/    public static Dialog submitWarn(final Context context, Spanned wareDesc,                                    final DialogInterface.OnClickListener onClickListener) {        BaseDialog.Builder builder = new BaseDialog.Builder(context) {            @Override            protected View getCenterView(View centerView, ViewGroup container) {                return centerView;            }        };        View view = View.inflate(context, R.layout.common_warn_dialog, null);        ((TextView) view.findViewById(R.id.dialog_hint)).setText(wareDesc);        builder.setCenterView(view)                .setPositiveButton("确定", new DialogInterface.OnClickListener() {                    @Override                    public void onClick(DialogInterface dialog, int which) {                        onClickListener.onClick(dialog, which);                    }                })                .setNegativeButton("取消", null);        builder.setTitle("提示");        return builder.create();    }    public static Dialog submitWarn(final Context context, String wareDesc,                                    final DialogInterface.OnClickListener onClickListener) {        return normal(context, "提示", wareDesc, "确定", "取消", onClickListener);    }    /**     * 确认退出登录警告     **/    public static Dialog logout(final Activity context, final DialogInterface.OnClickListener onClickListener) {        return normal(context, "提示", "确认退出登录?", "确定", "取消", onClickListener);    }    /**     * 未连接设备警告对话框     **/    public static Dialog connectDeviceWarn(final Context context, final DialogInterface.OnClickListener onClickListener) {        return normal(context, "提示", "当前未连接到设备,是否设置连接设备?", "去连接", "取消", onClickListener);    }    /**     * 确认通用警告     **/    public static Dialog normal(final Context context, String title, String msg, String okText,                                String cancelText, final DialogInterface.OnClickListener onClickListener) {        BaseDialog.Builder builder = new BaseDialog.Builder(context) {            @Override            protected View getCenterView(View centerView, ViewGroup container) {                return centerView;            }        };        View view = View.inflate(context, R.layout.common_warn_dialog, null);        ((TextView) view.findViewById(R.id.dialog_hint)).setText(msg);        builder.setCenterView(view);        if (!TextUtils.isEmpty(okText)) {            builder.setPositiveButton(okText, onClickListener);        }        builder.setNegativeButton(cancelText, null);        builder.setTitle(title);        return builder.create();    }    /**     * 退出编辑警告     **/    public static Dialog exitEdit(final Activity context) {        return normal(context, "提示", "确认退出编辑?", "确定", "取消", new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {                context.finish();            }        });    }}

上面activity的代码就可以改为:

public class DialogActivity extends AppCompatActivity {    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_dialog);    }    public void baseDialog(View view){        WarnDialog.connectDeviceWarn(DialogActivity.this, new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {                showWarnDialog("确认退出?");            }        }).show();    }    private void showWarnDialog(String warnDesc) {        WarnDialog.submitWarn(context, warnDesc, new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {                //做处理            }        }).show();    }}

看效果
这里写图片描述

就这么多了。用起来也很方便了。

0 0
原创粉丝点击