文章目录

  • AlertDialog(对话框)详解
    • 本节引言
    • 1.基本使用流程
    • 2.几种常用的对话框使用示例
    • 3.通过Builder的setView()定制显示的AlertDialog

AlertDialog(对话框)详解

本节引言

本节继续给大家带来是显示提示信息的第三个控件AlertDialog(对话框),同时它也是其他 Dialog 的父类!比如 ProgressDialog,TimePickerDialog等,而AlertDialog的父类是:Dialog! 另外,不像前面学习的 Toast 和 Notification,AlertDialog并不能直接new出来,如果你打开 AlertDialog的源码,会发现构造方法是protected的,如果我们要创建AlertDialog的话,我们 需要使用到该类中的一个静态内部类:public static class Builder,然后来调用AlertDialog 里的相关方法,来对AlertDialog进行定制,最后调用show()方法来显示我们的AlertDialog对话框! 好的,下面我们就来学习AlertDialog的基本用法,以及定制我们的AlertDialog! 官方文档:AlertDialog


1.基本使用流程

  • Step 1:创建AlertDialog.Builder对象;
  • Step 2:调用**setIcon()**设置图标,**setTitle()setCustomTitle()**设置标题;
  • Step 3:设置对话框的内容:**setMessage()**还有其他方法来指定显示的内容;
  • Step 4:调用**setPositive/Negative/NeutralButton()**设置:确定,取消,中立按钮;
  • Step 5:调用**create()方法创建这个对象,再调用show()**方法将对话框显示出来;

返回顶部


2.几种常用的对话框使用示例

运行效果图:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hhmhCzXO-1623112079612)(https://gitee.com/zyx201229/blogimages/raw/master/img/Android/20210608082732.jpeg)]

核心代码

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"tools:context=".basicItems.AlertDialog.AlertDialogActivity"><Buttonandroid:id="@+id/button4"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentStart="true"android:layout_alignParentTop="true"android:text="普通对话框" /><Buttonandroid:id="@+id/button5"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentStart="true"android:layout_alignParentTop="true"android:layout_marginTop="57dp"android:text="普通列表对话框" /><Buttonandroid:id="@+id/button6"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentStart="true"android:layout_alignParentTop="true"android:layout_marginStart="0dp"android:layout_marginTop="121dp"android:text="单选对话框" /><Buttonandroid:id="@+id/button7"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentStart="true"android:layout_alignParentTop="true"android:layout_marginStart="0dp"android:layout_marginTop="185dp"android:text="多选对话框" />
</RelativeLayout>

MainActivity.java

package com.example.learning.basicItems.AlertDialog;import androidx.appcompat.app.AppCompatActivity;import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.MultiAutoCompleteTextView;
import android.widget.Toast;import com.example.learning.R;public class AlertDialogActivity extends AppCompatActivity {// 声明组件Button button4, button5, button6, button7;private AlertDialog alert = null;private AlertDialog.Builder builder = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_alert_dialog);// 获取组件button4 = findViewById(R.id.button4);button5 = findViewById(R.id.button5);button6 = findViewById(R.id.button6);button7 = findViewById(R.id.button7);// 普通对话button4.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {// 创建对象alert = null;builder = new AlertDialog.Builder(AlertDialogActivity.this).setTitle("普通对话框").setIcon(R.mipmap.ic_launcher).setMessage("这是一个最普通的AlertDialog,\n带有三个按钮,分别是取消,中立和确定").setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(AlertDialogActivity.this, "你点击了确认按钮~", Toast.LENGTH_SHORT).show();alert.dismiss();}}).setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(AlertDialogActivity.this, "你点击了取消按钮~", Toast.LENGTH_SHORT).show();alert.dismiss();}}).setNeutralButton("中立", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(AlertDialogActivity.this, "你点击了中立按钮~", Toast.LENGTH_SHORT).show();alert.dismiss();}});// 创建 alertDialogalert = builder.create();// 展示 alertDialogalert.show();}});// 普通列表对话框String[] lesson = new String[]{"语文", "数学", "英语", "化学"};button5.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {alert = null;builder = new AlertDialog.Builder(AlertDialogActivity.this);builder.setTitle("普通列表对话框").setIcon(R.mipmap.ic_launcher).setItems(lesson, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(AlertDialogActivity.this, "你选择了" + lesson[which], Toast.LENGTH_SHORT).show();alert.dismiss();}});alert = builder.create();alert.show();}});String[] fruits = new String[]{"苹果", "橘子", "香蕉", "西瓜"};// 单选对话框button6.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {alert = null;builder = new AlertDialog.Builder(AlertDialogActivity.this);builder.setTitle("单选对话框,只能选择一个哦~").setIcon(R.mipmap.ic_launcher).setSingleChoiceItems(fruits, 0, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(AlertDialogActivity.this, "你选择了" + fruits[which], Toast.LENGTH_SHORT).show();}});alert = builder.create();alert.show();}});// 多选对话框CharSequence[] hobbies = new CharSequence[]{"打篮球", "游泳", "魔方", "卡林巴"};Boolean[] checkItems = new Boolean[]{false, false, false, false};// 单选对话框button7.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {alert = null;AlertDialog.Builder builder1 = new AlertDialog.Builder(AlertDialogActivity.this).setTitle("请添加爱好:").setIcon(R.mipmap.ic_launcher).setMultiChoiceItems(hobbies, checkItems, new DialogInterface.OnMultiChoiceClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which, boolean isChecked) {}}).setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {String result = "";for (int i = 0; i < checkItems.length ; i++) {if (checkItems[i]){result += hobbies[i] + " ";}}Toast.makeText(AlertDialogActivity.this, "您选择的爱好有:"+result, Toast.LENGTH_SHORT).show();}});alert = builder.create();alert.show();}});}
}

布局就是四个简单的按钮,这里就不贴出来了,用法非常简单~无非就是创建一个Builder对象后, 进行相关设置,然后create()生成一个AlertDialog对象,最后调用show()方法将AlertDialog 显示出来而已!另外,细心的你可能发现我们点击对话框的外部区域,对话框就会消失,我们 可以为builder设置**setCancelable(false)**即可解决这个问题!

返回顶部


3.通过Builder的setView()定制显示的AlertDialog

我们可以自定义一个与系统对话框不同的布局,然后调用setView()将我们的布局加载到 AlertDialog上,上面我们来实现这个效果:

运行效果图

关键代码

首先是两种不同按钮的selctor的drawable文件:

btn_selctor_exit.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"><item android:state_pressed="true" android:drawable="@mipmap/iv_icon_exit_pressed"/><item android:drawable="@mipmap/iv_icon_exit_normal"/>
</selector>

btn_selctor_choose.xml

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android"><item android:state_pressed="true" android:drawable="@mipmap/bg_btn_pressed"/><item android:drawable="@mipmap/bg_btn_normal"/>
</selector>

接着是自定义的Dialog布局:view_dialog_custom.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:id="@+id/RelativeLayout1"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><RelativeLayoutandroid:id="@+id/titlelayout"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_alignParentTop="true"android:background="#53CC66"android:padding="5dp"><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_centerVertical="true"android:text="提示信息"android:textColor="#ffffff"android:textSize="18sp"android:textStyle="bold" /><Buttonandroid:id="@+id/btn_cancle"android:layout_width="30dp"android:layout_height="30dp"android:layout_alignParentRight="true"android:background="@drawable/btn_selctor_exit" /></RelativeLayout><LinearLayoutandroid:id="@+id/ly_detail"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_below="@+id/titlelayout"android:layout_centerInParent="true"android:orientation="vertical"><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="10dp"android:layout_marginTop="20dp"android:text="通过setView()方法定制AlertDialog"android:textColor="#04AEDA"android:textSize="18sp" /><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_marginLeft="10dp"android:layout_marginTop="10dp"android:text="作者:Coder-pig"android:textColor="#04AEDA"android:textSize="18sp" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_below="@+id/ly_detail"android:layout_marginTop="10dp"android:orientation="horizontal"><Buttonandroid:id="@+id/btn_blog"android:layout_width="match_parent"android:layout_height="40dp"android:layout_margin="5dp"android:layout_weight="1"android:background="@drawable/btn_selctor_choose"android:text="访问博客"android:textColor="#ffffff"android:textSize="20sp" /><Buttonandroid:id="@+id/btn_close"android:layout_width="match_parent"android:layout_height="40dp"android:layout_margin="5dp"android:layout_weight="1"android:background="@drawable/btn_selctor_choose"android:text="关闭"android:textColor="#ffffff"android:textSize="20sp" /></LinearLayout></RelativeLayout>

最后是MainActivity.java

public class MainActivity extends AppCompatActivity {private Button btn_show;private View view_custom;private Context mContext;private AlertDialog alert = null;private AlertDialog.Builder builder = null;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mContext = MainActivity.this;btn_show = (Button) findViewById(R.id.btn_show);//初始化Builderbuilder = new AlertDialog.Builder(mContext);//加载自定义的那个View,同时设置下final LayoutInflater inflater = MainActivity.this.getLayoutInflater();view_custom = inflater.inflate(R.layout.view_dialog_custom, null,false);builder.setView(view_custom);builder.setCancelable(false);alert = builder.create();view_custom.findViewById(R.id.btn_cancle).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {alert.dismiss();}});view_custom.findViewById(R.id.btn_blog).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Toast.makeText(getApplicationContext(), "访问博客", Toast.LENGTH_SHORT).show();Uri uri = Uri.parse("http://blog.csdn.net/coder_pig");Intent intent = new Intent(Intent.ACTION_VIEW, uri);startActivity(intent);alert.dismiss();}});view_custom.findViewById(R.id.btn_close).setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {Toast.makeText(getApplicationContext(), "对话框已关闭~", Toast.LENGTH_SHORT).show();alert.dismiss();}});btn_show.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {alert.show();}});}
}

返回顶部


【Android 常见控件使用】AlertDialog(对话框)详解相关推荐

  1. android组件用法说明,Android第三方控件PhotoView使用方法详解

    Android第三方控件PhotoView使用方法详解 发布时间:2020-10-21 15:06:09 来源:脚本之家 阅读:74 作者:zhaihaohao1 PhotoView的简介: 这是一个 ...

  2. android控件使用大全,Android常见控件使用详解

    本文实例为大家分享了六种Android常见控件的使用方法,供大家参考,具体内容如下 1.TextView 主要用于界面上显示一段文本信息 2.Button 用于和用户交互的一个按钮控件 //为Butt ...

  3. Android基础入门教程——2.5.3 AlertDialog(对话框)详解

    Android基础入门教程--2.5.3 AlertDialog(对话框)详解 标签(空格分隔): Android基础入门教程 本节引言: 本节继续给大家带来是显示提示信息的第三个控件AlertDia ...

  4. android禁止下拉刷新,Android开发之无痕过渡下拉刷新控件的实现思路详解

    相信大家已经对下拉刷新熟悉得不能再熟悉了,市面上的下拉刷新琳琅满目,然而有很多在我看来略有缺陷,接下来我将说明一下存在的缺陷问题,然后提供一种思路来解决这一缺陷,废话不多说!往下看嘞! 1.市面一些下 ...

  5. ASP中利用OWC控件实现图表功能详解[zz]

    ASP中利用OWC控件实现图表功能详解 在ASP中利用OWC(Office Web Components)控件可轻松实现各种图表功能,如饼图,簇状柱型图,折线图等. 在下面的代码中我详细的给出了饼图, ...

  6. wxss 点击样式_微信小程序点击控件修改样式实例详解

    微信小程序点击控件修改样式实例详解 现在要在微信小程序中实现点击控件修改样式,如下: 微信小程序中不支持直接操作dom,要实现这种效果,我们需要通过设置data,然后利用数据和界面的双向绑定来实现它. ...

  7. ASP中利用OWC控件实现图表功能详解

    在ASP中利用OWC(Office Web Components)控件可轻松实现各种图表功能,如饼图,簇状柱型图,折线图等. 在下面的代码中我详细的给出了饼图,簇状柱型图,折线图的使用方法.OWC的更 ...

  8. java radiogroup_Android基础控件RadioGroup使用方法详解

    本文为大家分享了Android基础控件RadioGroup的使用,供大家参考,具体内容如下 1.简单介绍 RadioGroup可以提供几个选项供用户选择,但只能选择其中的一个.其下面可以横着或者竖着挂 ...

  9. 移动应用开发之路 04 Android Studio 5种控件介绍、实战详解

    学校开了一门移动应用开发课程,我一开始兴趣盎然,但是看到使用的环境是 Java 8 的时候心就凉了一半,在询问老师的意见之后决定使用现在比较常用的Android Studio完成学习,特此记录自学之路 ...

最新文章

  1. 用c语言编写心里测试,求各位大神赐教!我做了一个“心理测试的答题卷”编程,总共有1...
  2. 一键修改分辨率bat_求使用批处理BAT设置分辨率的方法介绍?
  3. Python Pyc文件
  4. 算法--组合数学:杨辉三角数学分析以及Java实现
  5. Android init.rc分析
  6. .h头文件 .lib库文件 .dll动态库文件之间的关系
  7. 二次注入 php,dedecms20140606 二次注入+存储型xss
  8. Bitmap文件格式+生成一个BMP文件
  9. Java循环删除集合多个元素的正确打开方式
  10. framebuffer[转之]
  11. java可以做苹果软件吗_Java应用软件iPhone上运行 苹果没兴趣Sun单干
  12. 关于对象的思考(二)
  13. 算法 —— 实用程序片段
  14. datetime与timestamp的区别
  15. 象棋名手手机版2019最新版_象棋名手
  16. Navicat Premium 12破解方法
  17. ActiveSync同步使用方法
  18. 局域网网络流量监控_【网络监控与安全】主要网络流量处理技术
  19. 明解C语言中级篇练习代码------第八章
  20. git cherry-pick操作

热门文章

  1. display:flex和display:block的区别
  2. Vue 报错 | warn ajv-keywords@3.2.0 requires a peer of ajv@^6.0.0 but none is installed. You must insta
  3. CentOS 8 yum安装、卸载、升级软件等命令
  4. 【愚公系列】2021年11月 攻防世界-进阶题-MISC-045(hong)
  5. 算法设计与分析基础 第五章谜题
  6. 视频超分:DUF(Deep Video Super-Resolution Network Using Dynamic Upsampling Filters Without ...)
  7. CentOs7 du、df、free
  8. Linux正则表达式 --已整理
  9. 使用scala轻松完成wordcount统计案例
  10. 使用CardView实现卡片式设计 (常用于RecyclerView中的item)