一、Dialog

我们首先来看看android官方文档对Dialog的介绍

A dialog is a small window that prompts the user to make a decision or enter additional information. A dialog does not fill the screen and is normally used for modal events that require users to take an action before they can proceed.

dialog就是一个在屏幕上弹出一个可以让用户做出一个选择,或者输入额外的信息的对话框,一个对话框并不会沾满我们整个的屏幕,并且通常用于模型事件当中需要用户做出一个决定后才会继续执行。

Dialog类是dialog对话框的基类,但是我们应该避免直接使用这个类来实例化一个dialog对话框,我们应当使用其子类来得到一个对话框:

java.lang.Object   ↳     android.app.DialogKnown Direct SubclassesAlertDialog, CharacterPickerDialog, MediaRouteChooserDialog, MediaRouteControllerDialog, PresentationKnown Indirect SubclassesDatePickerDialog, ProgressDialog, TimePickerDialog 

我们看到,Dialog有很多的子类实现,所以我们要定义一个对话框,使用其子类来实例化一个即可,而不要直接使用Dialog这个父类来构造。

二、AlertDialog

今天我们重点要来了解的就是AlertDialog对话框,我们看到,AlertDialog是Dialog的一个直接子类。

使用AlertDialog,我们可以显示一个标题,最多3个按钮操作,以及一组选择框或者是自己定义的弹出框。

这里借用android的官方文档提供的一个图来看看AlertDialog框的组成:

①区域1那里就是定义弹出框的头部信息,包括标题名或者是一个图标。

②区域2那里是AlertDialog对话框的content部分,在这里我们可以设置一些message信息,或者是定义一组选择框,还可以定义我们自己的布局弹出框。

③区域3那里使我们的Action Buttons部分,这里我们可以定义我们的操作按钮。

说到Action Buttons这里要特别注意一下:

在AlertDialog中,定义按钮都是通过 setXXXButton 方法来完成,其中一共有3种不同的Action Buttons供我们选择:

1.setPositiveButton(CharSequence text, DialogInterface.OnClickListener listener)这是一个相当于OK、确定操作的按钮,2.setNegativeButton (CharSequence text, DialogInterface.OnClickListener listener)这是一个相当于取消操作的按钮。3. setNeutralButton (CharSequence text, DialogInterface.OnClickListener listener)这个是相当于一个忽略操作的按钮。

我们每一种action buttons最多只能出现一个,即弹出对话框最多只能出现一个PositiveButton。

 

 

 开始介绍常见的对话框时先解决一个将要出现的bug

解决方法有两种:

1: 将DialogActivity 改为直接继承Activity

   import android.app.AlertDialog;

2: 根据提示来使用AppCompat的theme

android:theme="@style/Theme.AppCompat.Light.NoActionBar" />

 

三.常用的几种AlertDialog对话框

1.普通Dialog

   

 /**     * 普通Dialog     */    private void showNormalDialog() {        AlertDialog.Builder builder = new AlertDialog.Builder(CommonDialogActivity.this);        builder.setIcon(R.mipmap.ic_launcher);        builder.setTitle("弹出警告框");        builder.setMessage("确定删除吗?");        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {                Toast.makeText(CommonDialogActivity.this, "positive: " + which, Toast.LENGTH_SHORT).show();            }        });        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {                Toast.makeText(CommonDialogActivity.this, "negative: " + which, Toast.LENGTH_SHORT).show();            }        });        builder.setNeutralButton("忽略", new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {                Toast.makeText(CommonDialogActivity.this, "neutral: " + which, Toast.LENGTH_SHORT).show();            }        });        //    显示出该对话框        builder.show();    }

 

2.列表Dialog

   

 /**     * 列表Dialog     */    private void showListDialog() {        AlertDialog.Builder builder = new AlertDialog.Builder(CommonDialogActivity.this);        builder.setIcon(R.mipmap.ic_launcher);        builder.setTitle("选择一个城市");        //    指定下拉列表的显示数据        final String[] cities = {"广州", "上海", "北京", "深圳", "运城", "香港", "澳门"};        builder.setItems(cities, new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {                Toast.makeText(CommonDialogActivity.this, "您选择的城市是:" + cities[which], Toast.LENGTH_SHORT).show();            }        });        //    显示出该对话框        builder.show();    }

3.单选列表Dialog

   

   

   /**     * 单选列表Dialog     */   private int defaultValue;//默认值    private void showSingleChoiceDialog() {        AlertDialog.Builder builder = new AlertDialog.Builder(CommonDialogActivity.this);        builder.setIcon(R.mipmap.ic_launcher);        builder.setTitle("选择一个城市");        //    指定下拉列表的显示数据        final String[] cities = {"广州", "上海", "北京", "深圳", "运城", "香港", "澳门"};        /**         * 第一个参数指定我们要显示的一组下拉单选框的数据集合         * 第二个参数代表索引,指定默认哪一个单选框被勾选上         * 第三个参数给每一个单选项绑定一个监听器         */          defaultValue = 0;//默认值索引        builder.setSingleChoiceItems(cities, defaultValue, new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {                defaultValue = which;            }        });        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {                    Toast.makeText(CommonDialogActivity.this, "您选择了:"+cities[defaultValue], Toast.LENGTH_SHORT).show();            }        });        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {                Toast.makeText(CommonDialogActivity.this, "取消", Toast.LENGTH_SHORT).show();            }        });        //    显示出该对话框        builder.show();    }

4.多选dialog

    

  /**     * 多选dialog     */    private ArrayList yourChoices;    private void showMultiChoiceDialog() {        if (yourChoices==null){            yourChoices = new ArrayList<>();        }        yourChoices.clear();        AlertDialog.Builder builder = new AlertDialog.Builder(CommonDialogActivity.this);        builder.setIcon(R.mipmap.ic_launcher);        builder.setTitle("选择城市");        //    指定下拉列表的显示数据        final String[] cities = {"广州", "上海", "北京", "深圳", "运城", "香港", "澳门"};        // 设置默认选中的选项,全为false默认均未选中        final boolean initChoiceSets[]={false,false,false,false,false,false,false};        /**         * 第一个参数指定我们要显示的一组下拉多选框的数据集合         * 第二个参数代表哪几个选项被选择,如果是null,则表示一个都不选择,如果希望指定哪一个多选选项框被选择,         * 需要传递一个boolean[]数组进去,其长度要和第一个参数的长度相同,例如 {true, false, false, true};         * 第三个参数给每一个多选项绑定一个监听器         */        builder.setMultiChoiceItems(cities, initChoiceSets, new DialogInterface.OnMultiChoiceClickListener() {            @Override            public void onClick(DialogInterface dialog, int which, boolean isChecked) {                if (isChecked) {                    yourChoices.add(which);                } else {                    yourChoices.remove(which);                }            }        });        builder.setPositiveButton("确定",                new DialogInterface.OnClickListener() {                    @Override                    public void onClick(DialogInterface dialog, int which) {                        int size = yourChoices.size();                        String str = "";                        for (int i = 0; i < size; i++) {                            str += cities[yourChoices.get(i)] + " ";                        }                        if (size == 0){                            Toast.makeText(CommonDialogActivity.this,                                    "您还没有选择,请选择",                                    Toast.LENGTH_SHORT).show();                        }                        Toast.makeText(CommonDialogActivity.this,                                "你选中了" + str,                                Toast.LENGTH_SHORT).show();                    }                });        builder.show();    }

5.等待dialog

 /**     * 等待dialog     */    private void showWaitingDialog() {        /* 等待Dialog具有屏蔽其他控件的交互能力         * @setCancelable 为使屏幕不可点击,设置为不可取消(false)         * 下载等事件完成后,主动调用函数关闭该Dialog         */        final ProgressDialog waitingDialog=                new ProgressDialog(CommonDialogActivity.this);        waitingDialog.setTitle("我是一个等待Dialog");        waitingDialog.setMessage("等待中...");        waitingDialog.setCancelable(false);        waitingDialog.show();        new Thread(new Runnable() {            @Override            public void run() {                    try {                        Thread.sleep(1000);                    } catch (InterruptedException e){                        e.printStackTrace();                    }                // 1秒后窗口消失                waitingDialog.cancel();            }        }).start();    }

6.进度条dialog

 

    

 /**     * 进度条dialog     */    private void showProgressDialog() {        /* @setProgress 设置初始进度         * @setProgressStyle 设置样式(水平进度条)         * @setMax 设置进度最大值         */        final int MAX_PROGRESS = 100;        final ProgressDialog progressDialog =                new ProgressDialog(CommonDialogActivity.this);        progressDialog.setProgress(0);        progressDialog.setTitle("我是一个进度条Dialog");        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);        progressDialog.setMax(MAX_PROGRESS);        progressDialog.show();        /* 模拟进度增加的过程         * 新开一个线程,每个100ms,进度增加1         */        new Thread(new Runnable() {            @Override            public void run() {                int progress= 0;                while (progress < MAX_PROGRESS){                    try {                        Thread.sleep(100);                        progress++;                        progressDialog.setProgress(progress);                    } catch (InterruptedException e){                        e.printStackTrace();                    }                }                // 进度达到最大值后,窗口消失                progressDialog.cancel();            }        }).start();    }

7.编辑dialog

    

 /**     * 编辑dialog     */    private void showInputDialog() {        /*@setView 装入一个EditView         */        final EditText editText = new EditText(CommonDialogActivity.this);        AlertDialog.Builder inputDialog =                new AlertDialog.Builder(CommonDialogActivity.this);        inputDialog.setTitle("我是一个输入Dialog").setView(editText);        inputDialog.setPositiveButton("确定",                new DialogInterface.OnClickListener() {                    @Override                    public void onClick(DialogInterface dialog, int which) {                        Toast.makeText(CommonDialogActivity.this,                                editText.getText().toString(),                                Toast.LENGTH_SHORT).show();                    }                }).show();    }

8.自定义dialog

     

  /**     * 自定义dialog     */    private void showCustomizeDialog() {        AlertDialog.Builder builder = new AlertDialog.Builder(CommonDialogActivity.this);        builder.setIcon(R.mipmap.ic_launcher);        builder.setTitle("请输入用户名和密码");        //    通过LayoutInflater来加载一个xml的布局文件作为一个View对象        View view = LayoutInflater.from(CommonDialogActivity.this).inflate(R.layout.dialog, null);        //    设置我们自己定义的布局文件作为弹出框的Content        builder.setView(view);        final EditText username = (EditText) view.findViewById(R.id.username);        final EditText password = (EditText) view.findViewById(R.id.password);        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {                String a = username.getText().toString().trim();                String b = password.getText().toString().trim();                //    将输入的用户名和密码打印出来                Toast.makeText(CommonDialogActivity.this, "用户名: " + a + ", 密码: " + b, Toast.LENGTH_SHORT).show();            }        });        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {            }        });        builder.show();    }

9.重写特定方法的dialog

    /* 复写Builder的create和show函数,可以在Dialog显示前实现必要设置     * 例如初始化列表、默认选项等     * @create 第一次创建时调用     * @show 每次显示时调用     */    private void showListRepeatDialog() {        //    指定下拉列表的显示数据        final String[] cities = {"广州", "上海", "北京", "深圳", "运城", "香港", "澳门"};        AlertDialog.Builder builder = new AlertDialog.Builder(CommonDialogActivity.this) {            @Override            public AlertDialog create() {                cities[0] = "太原";                return super.create();            }            @Override            public AlertDialog show() {                cities[1] = "郑州";                return super.show();            }        };        builder.setIcon(R.mipmap.ic_launcher);        builder.setTitle("选择一个城市");        builder.setItems(cities, new DialogInterface.OnClickListener() {            @Override            public void onClick(DialogInterface dialog, int which) {                Toast.makeText(CommonDialogActivity.this, "您选择的城市是:" + cities[which], Toast.LENGTH_SHORT).show();            }        });        /* @setOnDismissListener Dialog销毁时调用         * @setOnCancelListener Dialog关闭时调用         */        builder.setOnDismissListener(new DialogInterface.OnDismissListener() {            public void onDismiss(DialogInterface dialog) {                Toast.makeText(getApplicationContext(),                        "Dialog被销毁了",                        Toast.LENGTH_SHORT).show();            }        });        //    显示出该对话框        builder.show();    }

 

demo下载地址

更多相关文章

  1. android 弹出带输入框的对话框
  2. android 常用对话框
  3. android之Button
  4. Android自定义对话框(Dialog)位置,大小
  5. Android路径大全
  6. android 状态栏显示运行图标
  7. android listview 调用sqlsite数据库显示数据
  8. android 常用对话框
  9. android滑轮选择控件——whell

随机推荐

  1. android 电池(一):锂电池基本原理篇
  2. 在Android中使用SharedPreferences保存简
  3. Android(安卓)Content Provider(内容提供
  4. Android(安卓)Debug Bridge(adb)
  5. 自定义ListView分割线
  6. Android数据篇(一)
  7. 编写android 注解解释器
  8. android 开源框架:Afinal
  9. Android(安卓)命令行手动编译打包详解
  10. android 电池(一):锂电池基本原理篇