Android常用对话框大全——Dialog

article/2025/10/29 9:22:20

唉!最近一直忙碌着写项目以至于都没有空出点时间来总结近期的学习,

记录学习到的东西…现在正好有时间了就该好好记录一下学习的过程了。

今天就来谈谈开发中经常用的到的一个控件——Dialog,对话框一般我们就用来提示一些信息给用户,

让用户自主选择,或者在一些操作不可逆的情况下我们提示用户是否继续操作,

下面就让我们一起来学习吧。老司机发车啦…

一:最简单的对话框

 AlertDialog dialog = new AlertDialog.Builder(this).setIcon(R.mipmap.icon)//设置标题的图片.setTitle("我是对话框")//设置对话框的标题.setMessage("我是对话框的内容")//设置对话框的内容//设置对话框的按钮.setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(MainActivity.this, "点击了取消按钮", Toast.LENGTH_SHORT).show();dialog.dismiss();}}).setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(MainActivity.this, "点击了确定的按钮", Toast.LENGTH_SHORT).show();dialog.dismiss();}}).create();dialog.show();

AlertDialog类中有一个静态内部类Builder。所以可以看出对话框使用了一个建造者模式在调用函数的时候就可以一直直点点点链式调用。 需要注意的是:NegativeButton这个按钮是在对话框的左边,PositiveButton在对话框的右边;如果你还想再加一个按钮也是可以的只需要在调用.setNeutralButton("第三个按钮",listener)即可。

二:列表对话框

当给用户的选择就那么几条路的时候,就可在对话框上放置一个列表供用户自己选择

		final String items[] = {"我是Item一", "我是Item二", "我是Item三", "我是Item四"};AlertDialog dialog = new AlertDialog.Builder(this).setIcon(R.mipmap.icon)//设置标题的图片.setTitle("列表对话框")//设置对话框的标题.setItems(items, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(MainActivity.this, items[which], Toast.LENGTH_SHORT).show();}}).setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.dismiss();}}).setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.dismiss();}}).create();dialog.show();

源码已经为我们预留好了设置方法,所以我们只需要调用.setItems()即可,第一个参数即要显示item的数组,第二个参数也就是点击item后的监听事件还是so easy的。

三:单选列表对话框,这个与列表对话框差不对是一样的只是它是单选

 final String items[] = {"我是Item一", "我是Item二", "我是Item三", "我是Item四"};AlertDialog dialog = new AlertDialog.Builder(this).setIcon(R.mipmap.icon)//设置标题的图片.setTitle("单选列表对话框")//设置对话框的标题.setSingleChoiceItems(items, 1, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {Toast.makeText(MainActivity.this, items[which], Toast.LENGTH_SHORT).show();}}).setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.dismiss();}}).setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.dismiss();}}).create();dialog.show();

.setSingleChoiceItems(items, 1, listener)第一个参数:设置单选的资源数组;第二个参数:设置默认选中哪一项。

四:既然有单选列表,那自然而然也就肯定有多选列表啦

final String items[] = {"我是Item一", "我是Item二", "我是Item三", "我是Item四"};final boolean checkedItems[] = {true, false, true, false};AlertDialog dialog = new AlertDialog.Builder(this).setIcon(R.mipmap.icon)//设置标题的图片.setTitle("多选对话框")//设置对话框的标题.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which, boolean isChecked) {checkedItems[which] = isChecked;}}).setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.dismiss();}}).setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {for (int i = 0; i < checkedItems.length; i++) {if (checkedItems[i]) {Toast.makeText(MainActivity.this, "选中了" + i, Toast.LENGTH_SHORT).show();}}dialog.dismiss();}}).create();dialog.show();

.setMultiChoiceItems(items, checkedItems, listener)//第一个参数:设置单选的资源;第二个参数:设置默认选中哪几项(数组);

五:或许上面几种对话框的款式都不是你需要或者喜欢的,那你肯定就需要开始自定义了;源码为我们提供了一个.setView()函数,这样我们就可以自定义对话框显示的内容了,如下代码:

View view = getLayoutInflater().inflate(R.layout.half_dialog_view, null);final EditText editText = (EditText) view.findViewById(R.id.dialog_edit);AlertDialog dialog = new AlertDialog.Builder(this).setIcon(R.mipmap.icon)//设置标题的图片.setTitle("半自定义对话框")//设置对话框的标题.setView(view).setNegativeButton("取消", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.dismiss();}}).setPositiveButton("确定", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {String content = editText.getText().toString();Toast.makeText(MainActivity.this, content, Toast.LENGTH_SHORT).show();dialog.dismiss();}}).create();dialog.show();

上面代码中half_dialog_view.xml中我就放置了一个EditText;在这里好多人在找自己布局中的控件时候经常报NullpointException,原因也很简单就是没有使用加载的布局.findViewbyId()。到了这一步基本上就能满足开发中80%的需求了,看官如果还不能满足那别急慢慢往下看。

六:完全自定义的对话框

上面我们说了可以通过调用.setView(view)方法,自定义其显示的内容;但是你会觉得这远远不够我还想把他的标题或者底部按钮给改了,那么就需要来个完全自定义了,如下:

  1. 首先我们需要自定义Dialog的style,让他自己本有的东西全部透明,然后在设置我们自己的内容就可以达到完全自定义的效果了。
	 <!--对话框的样式--><style name="NormalDialogStyle"><!--对话框背景 --><item name="android:windowBackground">@android:color/transparent</item><!--边框 --><item name="android:windowFrame">@null</item><!--没有标题 --><item name="android:windowNoTitle">true</item><!-- 是否浮现在Activity之上 --><item name="android:windowIsFloating">true</item><!--背景透明 --><item name="android:windowIsTranslucent">false</item><!-- 是否有覆盖 --><item name="android:windowContentOverlay">@null</item><!--进出的显示动画 --><item name="android:windowAnimationStyle">@style/normalDialogAnim</item><!--背景变暗--><item name="android:backgroundDimEnabled">true</item></style><!--对话框动画--><style name="normalDialogAnim" parent="android:Animation"><item name="@android:windowEnterAnimation">@anim/normal_dialog_enter</item><item name="@android:windowExitAnimation">@anim/normal_dialog_exit</item></style>
  1. 接下来就可以为对话框设置我们自定义的style了.
	/*** 自定义对话框*/private void customDialog() {final Dialog dialog = new Dialog(this, R.style.NormalDialogStyle);View view = View.inflate(this, R.layout.dialog_normal, null);TextView cancel = (TextView) view.findViewById(R.id.cancel);TextView confirm = (TextView) view.findViewById(R.id.confirm);dialog.setContentView(view);//使得点击对话框外部不消失对话框dialog.setCanceledOnTouchOutside(true);//设置对话框的大小view.setMinimumHeight((int) (ScreenSizeUtils.getInstance(this).getScreenHeight() * 0.23f));Window dialogWindow = dialog.getWindow();WindowManager.LayoutParams lp = dialogWindow.getAttributes();lp.width = (int) (ScreenSizeUtils.getInstance(this).getScreenWidth() * 0.75f);lp.height = WindowManager.LayoutParams.WRAP_CONTENT;lp.gravity = Gravity.CENTER;dialogWindow.setAttributes(lp);cancel.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {dialog.dismiss();}});confirm.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {dialog.dismiss();}});dialog.show();}

同样我门通过调用这个dialog.setContentView(view);就可以设置我们自己的布局了。所以现在关键就是码我们的布局了一起来看看效果图

既然是自定义对话框,那么就肯定要来弄一弄他的方方面面;

  • 这里使用到了一个工具类用来计算手机屏幕的宽高,如下代码:
public class ScreenSizeUtils {private static ScreenSizeUtils instance = null;private int screenWidth, screenHeight;public static ScreenSizeUtils getInstance(Context mContext) {if (instance == null) {synchronized (ScreenSizeUtils.class) {if (instance == null)instance = new ScreenSizeUtils(mContext);}}return instance;}private ScreenSizeUtils(Context mContext) {WindowManager manager = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);DisplayMetrics dm = new DisplayMetrics();manager.getDefaultDisplay().getMetrics(dm);screenWidth = dm.widthPixels;// 获取屏幕分辨率宽度screenHeight = dm.heightPixels;// 获取屏幕分辨率高度}//获取屏幕宽度public int getScreenWidth() {return screenWidth;}//获取屏幕高度public int getScreenHeight() {return screenHeight;}
}
  • 我们现在可以自定义对话框了,那么我们就来实现一个经常用到的一个底部选择对话框,来看下效果图吧:
  • 先来码这个对话框的布局,dialog_bottom.xml里面就放置了三个按钮。
<?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="@android:color/transparent"android:orientation="vertical"><Buttonandroid:layout_width="match_parent"android:layout_height="wrap_content"android:background="@drawable/round_corner"android:text="拍照" /><TextViewandroid:layout_width="match_parent"android:layout_height="1dp"android:layout_marginLeft="10dp"android:layout_marginRight="10dp"android:background="#ddd" /><Buttonandroid:layout_width="match_parent"android:layout_height="wrap_content"android:background="@drawable/round_corner"android:text="相册" /><Buttonandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="10dp"android:background="@drawable/round_corner"android:text="取消" /><Viewandroid:layout_width="match_parent"android:layout_height="15dp" />
</LinearLayout>
  • 接下来就可以为我们的对话框加载这个布局了
        Dialog dialog = new Dialog(this, R.style.NormalDialogStyle);View view = View.inflate(this, R.layout.dialog_bottom, null);dialog.setContentView(view);dialog.setCanceledOnTouchOutside(true);view.setMinimumHeight((int) (ScreenSizeUtils.getInstance(this).getScreenHeight() * 0.23f));Window dialogWindow = dialog.getWindow();WindowManager.LayoutParams lp = dialogWindow.getAttributes();lp.width = (int) (ScreenSizeUtils.getInstance(this).getScreenWidth() * 0.9f);lp.height = WindowManager.LayoutParams.WRAP_CONTENT;lp.gravity = Gravity.BOTTOM;dialogWindow.setAttributes(lp);dialog.show();

上面这一段带代码的关键就是将Dialog放置在屏幕底部lp.gravity = Gravity.BOTTOM;并设置他的宽度为屏幕的90%lp.width = (int) (ScreenSizeUtils.getInstance(this).getScreenWidth() * 0.9f);。相信大家之前都用的是popwindow来实现这个效果的,现在学会了这个是不是可以直接把他给替换了。哈哈…

七:圆形进度条对话框

1.这个就相对比较简单了

 ProgressDialog dialog = new ProgressDialog(this);dialog.setMessage("正在加载中");dialog.show();

2.当然我们也可以设置一个水平的进度条并显示当前进度,只需要把他的样式设置为ProgressDialog.STYLE_HORIZONTAL即可。

		final ProgressDialog dialog = new ProgressDialog(this);dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);dialog.setMessage("正在加载中");dialog.setMax(100);final Timer timer = new Timer();timer.schedule(new TimerTask() {int progress = 0;@Overridepublic void run() {dialog.setProgress(progress += 5);if (progress == 100) {timer.cancel();}}}, 0, 1000);dialog.show();

八:BottomSheetDialog,一个可以上下拖动的对话框使用方法和Dialog还是差不多的。

 BottomSheetDialog dialog = new BottomSheetDialog(this);View view = getLayoutInflater().inflate(R.layout.activity_main, null);dialog.setContentView(view);//设置显示的内容,我这为了方便就直接把主布局设置进去了。dialog.show();

BottomSheetDialog会根据你设置的View大小来计算默认显示出来的高度,内容越多显示的越多反之则越少。当显示的内容比较少的时候他默认显示一点,这个时候就比较蛋疼了所以我们就要让他一显示就默认全部展开。

		/*** 默认展开对话框*/final FrameLayout frameLayout = (FrameLayout) dialog.findViewById(android.support.design.R.id.design_bottom_sheet);frameLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {@Overridepublic void onGlobalLayout() {//获得BottomSheetBehaviorBottomSheetBehavior behavior = BottomSheetBehavior.from(frameLayout);//设置对话框的的状态behavior.setState(BottomSheetBehavior.STATE_EXPANDED);}});

BottomSheetDialog的操作基本上都是通过Behavior来设置的,所以关键就是获得他的Behavior;
这里还有小坑就是:当你向下滑动让他消失的时候,对话框是看不见了但是他却并没有dismiss需要在点击一次屏幕才能完全消失。下面给出解决办法:通过监听他的状态来手动dismiss();

 behavior.setBottomSheetCallback(new BottomSheetBehavior.BottomSheetCallback() {@Overridepublic void onStateChanged(@NonNull View bottomSheet, int newState) {if (newState == BottomSheetBehavior.STATE_HIDDEN)dialog.dismiss();}@Overridepublic void onSlide(@NonNull View bottomSheet, float slideOffset) {}});

Demo下载地址

说到这里基本上一些常用的Dialog就讲完了(ps:如有缺漏欢迎大家留言补充…),相信你也一定学习get到了。欢迎大家加入 QQ群一起来学习哦! (时不时有老司机开车哦…)

在这里插入图片描述


http://chatgpt.dhexx.cn/article/NILUqodf.shtml

相关文章

Android 对话框(Dialog)

对话框是提示用户做出决定或输入额外事件的小窗口。对话框不会填充屏幕&#xff0c;通常用于需要用户采取行动才能继续执行的模式事件。 Dialog类是对话框的基类&#xff0c;我们可以使用Dialog来构建一个对话框。但Android建议避免直接使用Dialog&#xff0c;而应该使用其子类…

android十大常用对话框

Android十大常用对话框 一、对话框效果二、代码 最近老师叫我们整理android常用的对话框&#xff0c;我整理了十种对话框&#xff0c;用于分享交流&#xff0c;希望指正&#xff01; 一、对话框效果 主界面 1.普通对话框 2.单选对话框 3.多选对话框 4.列表对话框 5.不带进…

Android常用的几种对话框

1文本提示对话框 AlertDialog.Builder b new AlertDialog.Builder(this);//this为上下文&#xff0c;如果在本类里显示&#xff0c;通常使用this b.setTitle("标题");/对话框标题 b.setMessage("可能会删除某个文件");//提示文本 …

Android对话框的详细介绍(提示对话框,自定义对话框)

简介&#xff1a; 我们都知道在Android开发中&#xff0c;当我们的程序在与用户交互时&#xff0c;用户会得到一定的反馈&#xff0c;其中以对话框的形式的反馈还是比较常见的&#xff0c;接下来我们来介绍几种常见的对话框的基本使用。 前置准备&#xff1a;&#xff08;文章…

WinInet 和 WinHttp 有何区别?

背景 WinInet和WinHttp是windows平台下提供了两套独立的网络库&#xff0c;按照微软官方的说法&#xff0c; WinInet的优势在于client-端的应用&#xff0c;而WinHttp更适用于server-端编程。从名称上我们可以看出WinHttp在Http协议应用方面要比WinInet更加专业&#xff0c;Win…

使用WinHTTP与服务器通讯

WinHTTP 的工作流程如下 一.初始化WinHTTP 在与服务器交互之前, 必须用调用WinHttpOpen进行初始化,WinHttpOpen创建一个会话,并返回该会话的句柄,接着有了这个句柄, WinHttpConnect就能指定一个目标服务器 注意:调用了WinHttpConnect并不意味着和服务器建立了真正的连接 二.打…

使用c++ winhttp实现post请求

winhttp是windows网络库&#xff0c;要测试自己写的post请求是否有效&#xff0c;首先得在postman上面建立一个可用的接口。我的如下。 代码思路如下&#xff1a; 1、首先使用WinHttpCrackUrl拆解链接&#xff0c;后面会使用到拆解出来的信息。 2、再使用WinHttpOpen初始化 3、…

HTTP HTTPS POST GET(包含curl版本和winhttp两种实现)

玩过抓包&#xff0c;网络协议分析的朋友肯定都知道http https post get&#xff0c;web端和用户的交互主要是通过post get完成的。 今天带给大家的是C版本的http https get post,只会易语言的朋友请移步。 我这里有两种实现&#xff1a; 1&#xff1a;libcurl实现的CHttpClien…

C++用winhttp实现https访问服务器

由于项目升级&#xff0c;在数据传输过程中需要经过OAuth2.0认证&#xff0c;访问服务器需要https协议。 首先&#xff0c;实现C代码访问https 服务器&#xff0c;实现Get和post功能&#xff0c;在网上搜索一通&#xff0c;发现各种各样的都有&#xff0c;有的很简单&#xff0…

实现HTTP协议Get、Post和文件上传功能——使用WinHttp接口实现

在《使用WinHttp接口实现HTTP协议Get、Post和文件上传功能》一文中&#xff0c;我已经比较详细地讲解了如何使用WinHttp接口实现各种协议。在最近的代码梳理中&#xff0c;我觉得Post和文件上传模块可以得到简化&#xff0c;于是几乎重写了这两个功能的代码。因为Get、Post和文…

使用WinINet和WinHTTP实现Http访问

Http访问有两种方式&#xff0c;GET和POST&#xff0c;就编程来说GET方式相对简单点&#xff0c;它不用向服务器提交数据&#xff0c;在这个例程中我使用POST方式&#xff0c;提交数据value1与value2&#xff0c;并从服务器得到他们的和&#xff08;value1 value2&#xff09;…

WinHttp.WinHttpRequest.5.1

Set oHttp CreateObject ( " WinHttp.WinHttpRequest.5.1 " )oHttp.Option( 6 ) 0 禁止自动Redirect&#xff0c;最关键的 oHttp.SetTimeouts 9999999 , 9999999 , 9999999 , 9999999 设置超时&#xff5e;和ServerXMLHTTP组件一样 oHttp.Open " GET &q…

Tinyhttpd for Windows

TinyHTTPd forWindows 前言 TinyHTTPd是一个开源的简易学习型的HTTP服务器&#xff0c;项目主页在&#xff1a;http://tinyhttpd.sourceforge.net/&#xff0c;源代码下载&#xff1a;https://sourceforge.net/projects/tinyhttpd/&#xff0c;因为是学习型的代码,已经有好多年…

windows安装http测试服务

祝您身体健康&#xff0c;前程似锦&#xff0c;小弟期待文章对您有帮助&#xff0c;也期待您的打赏: 目录 1. 下载 HttpMockServer工具 2. windows10 安装jdk1.8 3. jdk按照上面配置完环境变量后打开cmd&#xff0c;运行 4. 准备测试的响应数据 text.txt,内容如下: 5. 会弹…

C++ winhttp 实现文件下载器

本篇内容讲述 C winHttp 实现下载器的简单 demo&#xff0c;使用了 WinHttpOpen、WinHttpConnect、WinHttpOpenRequest、WinHttpSendRequest、WinHttpReceiveResponse、WinHttpQueryDataAvailable、WinHttpReadData、WinHttpCloseHandle 等函数。 版权声明&#xff1a;本文为C…

WinHTTP教程

最近有些忙&#xff0c;也没更新BLOG&#xff0c;这几天在捣鼓一个小玩意要用到WinHTTP API&#xff0c;发现资料很少&#xff0c;而且大都是些MFC封装的例子&#xff0c;看得我是一个头几个大。就把自己关于WinHTTP的学习总结了一下&#xff0c;仅供参考&#xff0c;各人理解可…

WinHttp c++ 介绍及应用

一、HTTP协议介绍 http协议的底层协议是TCP协议。TCP协议是基于数据流的传输方式。其又叫做“超文本传输协议”&#xff0c;为什么呢&#xff0c;因为它是将超文本标记语言(HTML)文档从Web服务器传送到客户端的浏览器&#xff0c;通过因特网传送万维网文档的数据传送协议。 1…

WinHTTP

记录WinHTTP学习过程 一、什么是WinHTTP&#xff1f; WinHTTP的全称是Microsoft Windows HTTP Services&#xff0c; 它提供给开发者一个HTTP客户端应用程序接口(API)&#xff0c;通过这种API借助HTTP协议给其他的HTTP服务器发送请求。 二、WinHTTP访问流程 如上图&#xff0c;…

Java递归算法计算5的阶乘

递归 package com.etime.test019; //计算5的阶乘&#xff1b; public class Test15 {public static void main(String[] args) {//调用test1方法&#xff0c;且只调用一次int i test1(5);System.out.println(i);}//定义一个int类型返回值的静态方法public static int test1(i…

Java算法递归与递推

Java算法----递归与递推 递推实现递推思想递归实现递归思想递归实现递推思想递推实现递归思想四种方法的特点思维拓展 问题&#xff1a;给你一个整数n&#xff0c;如果n是奇数&#xff0c;就进行运算nn*31&#xff0c;如果n是偶数&#xff0c;就进行运算nn/2&#xff0c;直到n等…