android 对话框

android 8种对话框(Dialog)使用方法汇总

作者:@gzdaijie
本文为作者原创,转载请注明出处:https://www.cnblogs.com/gzdaijie/p/5222191.html

目录

1.写在前面
2.代码示例
2.1 普通Dialog(图1与图2)
2.2 列表Dialog(图3)
2.3 单选Dialog(图4)
2.4 多选Dialog(图5)
2.5 等待Dialog(图6)
2.6 进度条Dialog(图7)
2.7 编辑Dialog(图8)
2.8 自定义Dialog(图9)
3.复写回调函数

博客逐步迁移至 呆兔兔的小站

1.写在前面

  • Android提供了丰富的Dialog函数,本文介绍最常用的8种对话框的使用方法,包括普通(包含提示消息和按钮)、列表、单选、多选、等待、进度条、编辑、自定义等多种形式,将在第2部分介绍。
  • 有时,我们希望在对话框创建或关闭时完成一些特定的功能,这需要复写Dialog的create()show()dismiss()等方法,将在第3部分介绍。

2.代码示例

图片示例

2.1 普通Dialog(图1与图2)

  • 2个按钮
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button buttonNormal = (Button) findViewById(R.id.button_normal);
        buttonNormal.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showNormalDialog();
            }
        });
    }
     
    private void showNormalDialog(){
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象,因此可以链式设置属性
         */
        final AlertDialog.Builder normalDialog =
            new AlertDialog.Builder(MainActivity.this);
        normalDialog.setIcon(R.drawable.icon_dialog);
        normalDialog.setTitle("我是一个普通Dialog")
        normalDialog.setMessage("你要点击哪一个按钮呢?");
        normalDialog.setPositiveButton("确定",
            new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //...To-do
            }
        });
        normalDialog.setNegativeButton("关闭",
            new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //...To-do
            }
        });
        // 显示
        normalDialog.show();
    }
}
  • 3个按钮
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/* @setNeutralButton 设置中间的按钮
 * 若只需一个按钮,仅设置 setPositiveButton 即可
 */
private void showMultiBtnDialog(){
    AlertDialog.Builder normalDialog =
        new AlertDialog.Builder(MainActivity.this);
    normalDialog.setIcon(R.drawable.icon_dialog);
    normalDialog.setTitle("我是一个普通Dialog").setMessage("你要点击哪一个按钮呢?");
    normalDialog.setPositiveButton("按钮1",
        new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // ...To-do
        }
    });
    normalDialog.setNeutralButton("按钮2",
        new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // ...To-do
        }
    });
    normalDialog.setNegativeButton("按钮3", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // ...To-do
        }
    });
    // 创建实例并显示
    normalDialog.show();
}

2.2 列表Dialog(图3)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private void showListDialog() {
    final String[] items = { "我是1","我是2","我是3","我是4" };
    AlertDialog.Builder listDialog =
        new AlertDialog.Builder(MainActivity.this);
    listDialog.setTitle("我是一个列表Dialog");
    listDialog.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // which 下标从0开始
            // ...To-do
            Toast.makeText(MainActivity.this,
                "你点击了" + items[which],
                Toast.LENGTH_SHORT).show();
        }
    });
    listDialog.show();
}

2.3 单选Dialog(图4)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
int yourChoice;
private void showSingleChoiceDialog(){
    final String[] items = { "我是1","我是2","我是3","我是4" };
    yourChoice = -1;
    AlertDialog.Builder singleChoiceDialog =
        new AlertDialog.Builder(MainActivity.this);
    singleChoiceDialog.setTitle("我是一个单选Dialog");
    // 第二个参数是默认选项,此处设置为0
    singleChoiceDialog.setSingleChoiceItems(items, 0,
        new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            yourChoice = which;
        }
    });
    singleChoiceDialog.setPositiveButton("确定",
        new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if (yourChoice != -1) {
                Toast.makeText(MainActivity.this,
                "你选择了" + items[yourChoice],
                Toast.LENGTH_SHORT).show();
            }
        }
    });
    singleChoiceDialog.show();
}

2.4 多选Dialog(图5)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
ArrayList<Integer> yourChoices = new ArrayList<>();
private void showMultiChoiceDialog() {
    final String[] items = { "我是1","我是2","我是3","我是4" };
    // 设置默认选中的选项,全为false默认均未选中
    final boolean initChoiceSets[]={false,false,false,false};
    yourChoices.clear();
    AlertDialog.Builder multiChoiceDialog =
        new AlertDialog.Builder(MainActivity.this);
    multiChoiceDialog.setTitle("我是一个多选Dialog");
    multiChoiceDialog.setMultiChoiceItems(items, initChoiceSets,
        new DialogInterface.OnMultiChoiceClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which,
            boolean isChecked) {
            if (isChecked) {
                yourChoices.add(which);
            } else {
                yourChoices.remove(which);
            }
        }
    });
    multiChoiceDialog.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 += items[yourChoices.get(i)] + " ";
            }
            Toast.makeText(MainActivity.this,
                "你选中了" + str,
                Toast.LENGTH_SHORT).show();
        }
    });
    multiChoiceDialog.show();
}

2.5 等待Dialog(图6)

1
2
3
4
5
6
7
8
9
10
11
12
13
private void showWaitingDialog() {
    /* 等待Dialog具有屏蔽其他控件的交互能力
     * @setCancelable 为使屏幕不可点击,设置为不可取消(false)
     * 下载等事件完成后,主动调用函数关闭该Dialog
     */
    ProgressDialog waitingDialog=
        new ProgressDialog(MainActivity.this);
    waitingDialog.setTitle("我是一个等待Dialog");
    waitingDialog.setMessage("等待中...");
    waitingDialog.setIndeterminate(true);
    waitingDialog.setCancelable(false);
    waitingDialog.show();
}

2.6 进度条Dialog(图7)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
private void showProgressDialog() {
    /* @setProgress 设置初始进度
     * @setProgressStyle 设置样式(水平进度条)
     * @setMax 设置进度最大值
     */
    final int MAX_PROGRESS = 100;
    final ProgressDialog progressDialog =
        new ProgressDialog(MainActivity.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();
}

2.7 编辑Dialog(图8)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private void showInputDialog() {
    /*@setView 装入一个EditView
     */
    final EditText editText = new EditText(MainActivity.this);
    AlertDialog.Builder inputDialog =
        new AlertDialog.Builder(MainActivity.this);
    inputDialog.setTitle("我是一个输入Dialog").setView(editText);
    inputDialog.setPositiveButton("确定",
        new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Toast.makeText(MainActivity.this,
            editText.getText().toString(),
            Toast.LENGTH_SHORT).show();
        }
    }).show();
}

2.8 自定义Dialog(图9)

1
2
3
4
5
6
7
8
9
10
11
12
<!-- res/layout/dialog_customize.xml-->
<!-- 自定义View -->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <EditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        />
</LinearLayout>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
private void showCustomizeDialog() {
    /* @setView 装入自定义View ==> R.layout.dialog_customize
     * 由于dialog_customize.xml只放置了一个EditView,因此和图8一样
     * dialog_customize.xml可自定义更复杂的View
     */
    AlertDialog.Builder customizeDialog =
        new AlertDialog.Builder(MainActivity.this);
    final View dialogView = LayoutInflater.from(MainActivity.this)
        .inflate(R.layout.dialog_customize,null);
    customizeDialog.setTitle("我是一个自定义Dialog");
    customizeDialog.setView(dialogView);
    customizeDialog.setPositiveButton("确定",
        new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // 获取EditView中的输入内容
            EditText edit_text =
                (EditText) dialogView.findViewById(R.id.edit_text);
            Toast.makeText(MainActivity.this,
                edit_text.getText().toString(),
                Toast.LENGTH_SHORT).show();
        }
    });
    customizeDialog.show();
}

3.复写回调函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/* 复写Builder的create和show函数,可以在Dialog显示前实现必要设置
 * 例如初始化列表、默认选项等
 * @create 第一次创建时调用
 * @show 每次显示时调用
 */
private void showListDialog() {
    final String[] items = { "我是1","我是2","我是3","我是4" };
    AlertDialog.Builder listDialog =
        new AlertDialog.Builder(MainActivity.this){
         
        @Override
        public AlertDialog create() {
            items[0] = "我是No.1";
            return super.create();
        }
        @Override
        public AlertDialog show() {
            items[1] = "我是No.2";
            return super.show();
        }
    };
    listDialog.setTitle("我是一个列表Dialog");
    listDialog.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // ...To-do
        }
    });
    /* @setOnDismissListener Dialog销毁时调用
     * @setOnCancelListener Dialog关闭时调用
     */
    listDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
        public void onDismiss(DialogInterface dialog) {
            Toast.makeText(getApplicationContext(),
                "Dialog被销毁了",
                Toast.LENGTH_SHORT).show();
        }
    });
    listDialog.show();
}

转载于:https://www.cnblogs.com/z2qfei/p/7833226.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/251521.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Java 多线程 之 suspend挂起 线程实例

http://www.verejava.com/?id16992945731073 package com.suspend.resume; /*题目: 人们在火车站的售票窗口排队买火车票1. 北京西站开门2. 打开售票窗口3. 北京西站有10张去长沙的票4. 打开2个售票窗口, 5 假设每个售票窗口每隔1秒钟买完一张票1. 根据 名词 找类人们(Person…

算法 --- 插入排序的JS实现

let A [5, 2, 4, 6, 1 ,3];// 插入排序 insertionSort (A) > {console.log("原数组>>>", A);for (let j1; j<A.length; j) {let key A[j];i j -1;while ( i > -1 && A[i] > key) {A[i1] A[i];i i-1;}A[i 1] key;}console.log(&q…

SAFESHE错误

今天写驱动编译的时候遇到一个问题&#xff0c;link一个比较老的lib时&#xff0c;报错&#xff1a; error LNK2026: module unsafe for SAFESEH image 解决办法&#xff1a; 在Source文件中加入一行 NO_SAFESEHTRUE 编译时候执行 build -cZg转载于:https://www.cnblogs.com/fa…

python之正则(一)

1.常用正则表达式: \d:数字[0-9] &#xff0c;实例:a\dc -> a1c\D:非数字[^\d],实例:a\Dc -> abc\s:空白字符[<空格>\t\r\n\f\v] 实例:a\sc ->a c\S:非空白字符[^\s] 实例:a\Sc ->abc\w:单词字符[A-Za-z0-9_] 实例:a\wc ->abc\W:非单词字符[^\W] *:匹配前…

逻辑读、物理读

逻辑读、物理读、预读的基本概念转载于:https://www.cnblogs.com/mySerilBlog/p/9208215.html

算法 --- 归并排序的js实现

let mergeSort (A, p, q, r) > {console.log("原数组>>>", A);let n1 q - p 1;let n2 r - q;let L new Array();let R new Array();for (let i 1; i < n1 1; i) {L[i -1] A[p i - 1];}for (let j 1; j < n2 1; j) {R[j-1] A[q j];}L[…

c#中的代理和事件

事件&#xff08;event&#xff09;是一个非常重要的概念&#xff0c;我们的程序时刻都在触发和接收着各种事件&#xff1a;鼠标点击事件&#xff0c;键盘事件&#xff0c;以及处理操作系统的各种事件。所谓事件就是由某个对象发出的消息。比如用户按下了某个按钮&#xff0c;某…

个人技术博客

一. Volley框架 在进行和服务器交互的时候需要发送请求&#xff0c;发现了volley这个好用易上手的框架。volley是一个异步网络通信框架&#xff0c;它的优点在于轻量级、适用于量小但传送频繁的请求操作 搭建请求的第一步就是新建一个请求队列RequestQueue queue Volley.newRe…

软件构造 第一章第二节 软件开发的质量属性

​软件构造 第一章第二节 软件开发的质量属性 1.软件系统质量指标 External quality factors affect users 外部质量因素影响用户 Internal quality factors affect the software itself and its developers 内部质量因素影响软件本身和它的开发者 External quality results fr…

css --- 让不同的浏览器加载不同的CSS

// 通过条件注释让不同的浏览器加载不同的CSS <!--[if !IE]><!--> 除IE外都可识别 <!--<![endif]--> <!--[if IE]><!--> 所有的IE可识别 <![endif]--> <!--[if IE 6]> 仅IE6可识别 <![endif]--> <!--[if lt IE 6]> I…

정규식 문법 정리.초급

abcdefg a검색 abca abcbca abcabcdeda Cc 한개 캐릭터 [a] [ac] [a-c] [Cc] 수량자 1>* ( 0~무한대) 2> (1~무한대) 3.? () 4 {1,2} {Min,Max} [패턴]*{} 수량자.패턴…

css自媒体查询

准备工作1&#xff1a;设置Meta标签 首先我们在使用Media的时候需要先设置下面这段代码&#xff0c;来兼容移动设备的展示效果&#xff1a; <meta name"viewport" content"widthdevice-width, initial-scale1.0, maximum-scale1.0, user-scalableno">…

css --- 清除浮动

有时我们需要用到浮动,但又不想由于浮动的某些特性影响布局,这时就需要清除浮动 清除浮动主要应用的是CSS中的clear属性,clear属性定义了元素的哪一侧不允许出现浮动元素. 下面是两种应用比较广泛的清除浮动的方法: // 在需要的地方添加定义了clear:both的空标签 <style>…

数据可视化实现技术(canvas/svg/webGL)

数据可视化的实现技术和工具比较转载于:https://www.cnblogs.com/knuzy/p/9215632.html

Python 字符串操作(string替换、删除、截取、复制、连接、比较、查找、包含、大小写转换、分割等)...

http://www.cnblogs.com/huangcong/archis.strip() .lstrip() .rstrip(,) 去空格及特殊符号复制字符串Python1 #strcpy(sStr1,sStr2)2 sStr1 strcpy3 sStr2 sStr14 sStr1 strcpy25 print sStr2连接字符串Python1 #strcat(sStr1,sStr2)2 sStr1 strcat3 sStr2 append4 sStr1…

java 将一个非空文件夹拷贝到另一个地方

没有处理异常&#xff0c;只是简单的抛出了。需要捕获的需修改一下。 public class Test001 { //把一个文件夹或文件移到另一个地方去。 public static void main(String[] args) throws Exception { File filenew File("D:\\testFolder"); new Test001().copyFileTo…

Python环境 及安装

windows 1、下载安装包 https://www.python.org/downloads/2、安装默认安装路径&#xff1a;C:\python273、配置环境变量【右键计算机】--》【属性】--》【高级系统设置】--》【高级】--》【环境变量】--》【在第二个内容框中找到 变量名为Path 的一行&#xff0c;双击】 -->…

MUI主界面菜单同时移动主体部分不出滚动条解决

mOffcanvas(侧滑导航-主界面、菜单同时移动) 生成代码 增加列表滚动OK 增加幻灯片就挂了 百度了半天 没发现问题 后来想起官网的一句话 除顶部导航、底部选项卡两个控件之外&#xff0c;其它控件都建议放在.mui-content控件内&#xff0c;在Hbuilder中输入mbody&#xff0c;可快…

范围查询 BETWEEN AND

查询&#xff1a;从表t_student里 查找 id 在1~10 之间的学生信息&#xff0c;并显示 id,name,age,email 信息 SELECT id,name,age,email FROM t_student WHERE id BETWEEN 1 AND 10转载于:https://www.cnblogs.com/hello-dummy/p/9216720.html

css --- 应用媒介查询制作响应式导航栏

以上导航会自动适应各个尺寸的屏幕 代码如下: <!DOCTYPE html> <html> <head> <meta charset"utf-8"> <meta name"viewport" content"widthdevice-width, initial-scale1.0"> <meta name"apple-mobile-w…