Android常用实例—Alert Dialog的使用
Android常用实例—Alert Dialog的使用
AlertDialog的使用很普遍,在应用中当你想要用户做出“是”或“否”或者其它各式各样的选择时,为了保持在同样的Activity和不改变用户屏幕,就可以使用AlertDialog.
代码地址
https://github.com/JueYingCoder/AndroidUsefulExample_AlertDialog
这篇文章主要讲解如何实现各种AlertDialog,文章比较长,如果能认真读完,AlertDialog的各种用法应该就能掌握了,下面是我们今天要实现的最终效果:
乍一看,在应用中我们见过很多千奇百怪的对话框,但仔细分析,它还是有规律可循的,不外乎那几种,我们要学会从简易处着手,抽丝剥茧来掌握一项看起来似乎很复杂的功能。只要我们理清了基本逻辑,其他的根据需要适当改造就可以为我们所用了!
AlertDialog基本的结构如下:
可以将对话框主要分为三个部分:上面区域是标题栏和图标,中间区域是内容区,下方是button区;其他形式各异的对话框也都是基于此的变体而已!
那么要创建一个对话框,我们需要做些什么:
1,首先需要创建一个AlertDialog.Builder对象,基本语法:
AlertDialog.Builder alertDialogBuilder=new AlertDialog.Builder(this);
2,创建alertDialogBuilder对象后,通过调用它的create()方法就可以构造出一个对话框
AlertDialog alertDialog = alertDialogBuilder.create();alertDialog.show();//将dialog显示出来
3,但是我们还有一个疑问,如何设置Dialog的其他属性呢,也就是说怎么控制标题,图表区域,内容区域和button区域,我们自然而然的想到的是一系列set方法;事实上真是如此,通过调用alertDialogBuilder对象的setXX方法来实现:
alertDialogBuilder.setTitle();//设置标题alertDialogBuilder.setIcon();//设置图表/*设置下方按钮*/alertDialogBuilder.setPositiveButton();alertDialogBuilder.setNegativeButton();alertDialogBuilder.setNeutralButton();/*对话框内容区域的设置提供了多种方法*/setMessage();//设置显示文本setItems();//设置对话框内容为简单列表项setSingleChoiceItems();//设置对话框内容为单选列表项setMultiChoiceItems();//设置对话框内容为多选列表项setAdapter();//设置对话框内容为自定义列表项setView();//设置对话框内容为自定义View//设置对话框是否可取消setCancelable(booleab cancelable);setCancelListener(onCancelListener);
综上:对于AlertDialog的使用其实主要还是针对如何设置内容区域;
下面我们通过使用不同的内容区域的设置方法,实现几个常用的对话框;
基本思路是在MainActivity中添加几个Button,点击后分别弹出对应的AlertDialog
步骤:
- 1 .创建Android Project->”AlertDialogDemo”
- 2 .编写activity_main.xml布局文件
- 3.编写所需strings.xml
- 4.编写MainActivity中各方法
限于篇幅的问题,现只贴出关键性部分代码,其余的请读者自行实现;
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:orientation="vertical"android:layout_width="match_parent"android:layout_height="match_parent" ><Buttonandroid:id="@+id/btn_simple_dialog"android:text="@string/simple_dialog"android:textColor="#ffffff"android:textSize="18sp"android:background="#449F1D"android:layout_marginTop="10dp"android:layout_marginLeft="50dp"android:layout_marginRight="50dp"android:layout_width="match_parent"android:layout_height="wrap_content" /><Buttonandroid:id="@+id/btn_simple_list_dialog"android:text="@string/simple_list_dialog"android:textColor="#ffffff"android:textSize="18sp"android:background="#449F1D"android:layout_marginTop="10dp"android:layout_marginLeft="50dp"android:layout_marginRight="50dp"android:layout_width="match_parent"android:layout_height="wrap_content" /><Buttonandroid:id="@+id/btn_single_choice_dialog"android:text="@string/single_choice_dialog"android:textColor="#ffffff"android:textSize="18sp"android:background="#449F1D"android:layout_marginTop="10dp"android:layout_marginLeft="50dp"android:layout_marginRight="50dp"android:layout_width="match_parent"android:layout_height="wrap_content" /><Buttonandroid:id="@+id/btn_multi_choice_dialog"android:text="@string/multi_choice_dialog"android:textColor="#ffffff"android:textSize="18sp"android:background="#449F1D"android:layout_marginTop="10dp"android:layout_marginLeft="50dp"android:layout_marginRight="50dp"android:layout_width="match_parent"android:layout_height="wrap_content" /><Buttonandroid:id="@+id/btn_custom_adapter_dialog"android:text="@string/custom_adapter_dialog"android:textColor="#ffffff"android:textSize="18sp"android:background="#449F1D"android:layout_marginTop="10dp"android:layout_marginLeft="50dp"android:layout_marginRight="50dp"android:layout_width="match_parent"android:layout_height="wrap_content" /><Buttonandroid:id="@+id/btn_custom_view_dialog"android:text="@string/custom_view_dialog"android:textColor="#ffffff"android:textSize="18sp"android:background="#449F1D"android:layout_marginTop="10dp"android:layout_marginLeft="50dp"android:layout_marginRight="50dp"android:layout_width="match_parent"android:layout_height="wrap_content" />
</LinearLayout>
布局效果:
strings.xml
<resources><string name="app_name">ALertDialogDemo</string><!-- 主界面布局所需要的字符串资源--><string name="action_settings">Settings</string><string name="simple_dialog">基本对话框</string><string name="simple_list_dialog">简单列表对话框</string><string name="single_choice_dialog">单选项列表对话框</string><string name="multi_choice_dialog">多选项列表对话框</string><string name="custom_adapter_dialog">自定义Adapter对话框</string><string name="custom_view_dialog">自定义View对话框</string><!-- 对话框所需要的字符串资源--><string name="dialog_message">这里是内容区域</string><string name="postive_button">确定</string><string name="negative_button">取消</string><!-- 对话框提示信息字符串资源--><string name="toast_postive">你点击了确定按钮</string><string name="toast_negative">你点击了取消按钮</string><string name="text">自定义Adapter的内容</string></resources>
MainActivity.java
public class MainActivity extends ActionBarActivity implements View.OnClickListener{//对应各个buttonprivate Button simpleDiaog;private Button simpleListDiaog;private Button singleChoiceDiaog;private Button multiChoiceDiaog;private Button customAdateprDiaog;private Button customViewDiaog;//声明一个AlertDialog构造器private AlertDialog.Builder builder;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);//实例化控件simpleDiaog= (Button) findViewById(R.id.btn_simple_dialog);simpleListDiaog= (Button) findViewById(R.id.btn_simple_list_dialog);singleChoiceDiaog= (Button) findViewById(R.id.btn_single_choice_dialog);multiChoiceDiaog= (Button) findViewById(R.id.btn_multi_choice_dialog);customAdateprDiaog= (Button) findViewById(R.id.btn_custom_adapter_dialog);customViewDiaog= (Button) findViewById(R.id.btn_custom_view_dialog);//监听点击事件simpleDiaog.setOnClickListener(this);simpleListDiaog.setOnClickListener(this);singleChoiceDiaog.setOnClickListener(this);multiChoiceDiaog.setOnClickListener(this);customAdateprDiaog.setOnClickListener(this);customViewDiaog.setOnClickListener(this);}/*** * 每个button点击后弹出对应对话框,为了方便,各写一个showXXDialog()方法*/@Overridepublic void onClick(View view) {switch (view.getId()){case R.id.btn_simple_dialog:showSimpleDialog(view);break;case R.id.btn_simple_list_dialog:showSimpleListDialog(view);break;case R.id.btn_single_choice_dialog:showSingleChoiceDialog(view);break;case R.id.btn_multi_choice_dialog:showMultiChoiceDialog(view);break;case R.id.btn_custom_adapter_dialog:showCustomAdapterDialog(view);break;case R.id.btn_custom_view_dialog:showCustomViewDialog(view);break;}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.menu_main, menu);return true;}}
上述代码都比较简单,现在我们真正关心的就是如何去具体实现showXXDialog;
1.showSimpleDialog()
: 根据我们前面所写的基本语法,我们可以很快写出下面这些代码,唯一需要注意的就是监听两个button,由于这是最基本也是最核心的AlertDialog,所以只要掌握了这个其他的alertDialog也就相对简单了;
//显示基本Dialogprivate void showSimpleDialog(View view) {builder=new AlertDialog.Builder(this);builder.setIcon(R.mipmap.ic_launcher);builder.setTitle(R.string.simple_dialog);builder.setMessage(R.string.dialog_message);//监听下方button点击事件builder.setPositiveButton(R.string.postive_button, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialogInterface, int i) {Toast.makeText(getApplicationContext(),R.string.toast_postive,Toast.LENGTH_SHORT).show();}});builder.setNegativeButton(R.string.negative_button, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialogInterface, int i) {Toast.makeText(getApplicationContext(), R.string.toast_negative, Toast.LENGTH_SHORT).show();}});//设置对话框是可取消的builder.setCancelable(true);AlertDialog dialog=builder.create();dialog.show();}
实现效果:
2,showSimpleListDialog()
:前面的代码很相似,唯一需要改变的就是将内容区域改为列表项:
private void showSimpleListDialog(View view) {builder=new AlertDialog.Builder(this);builder.setIcon(R.mipmap.ic_launcher);builder.setTitle(R.string.simple_list_dialog);/*** 设置内容区域为简单列表项*/final String[] Items={"Items_one","Items_two","Items_three"};builder.setItems(Items, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialogInterface, int i) {Toast.makeText(getApplicationContext(), "You clicked "+Items[i], Toast.LENGTH_SHORT).show();}});builder.setCancelable(true);AlertDialog dialog=builder.create();dialog.show();}
实现效果:
3,showSingleChoiceDialog()
:注意setSingleChoiceItems()内部各参数的意义
private void showSingleChoiceDialog(View view) {builder=new AlertDialog.Builder(this);builder.setIcon(R.mipmap.ic_launcher);builder.setTitle(R.string.single_choice_dialog);/*** 设置内容区域为单选列表项*/final String[] items={"Items_one","Items_two","Items_three"};builder.setSingleChoiceItems(items, 1, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialogInterface, int i) {Toast.makeText(getApplicationContext(), "You clicked "+items[i], Toast.LENGTH_SHORT).show();}});builder.setCancelable(true);AlertDialog dialog=builder.create();dialog.show();}
实现效果:
4,showMultiCHoiceDialog()
:
private void showMultiChoiceDialog(View view) {builder=new AlertDialog.Builder(this);builder.setIcon(R.mipmap.ic_launcher);builder.setTitle(R.string.simple_list_dialog);/*** 设置内容区域为多选列表项*/final String[] items={"Items_one","Items_two","Items_three"};builder.setMultiChoiceItems(items, new boolean[]{true, false, true}, new DialogInterface.OnMultiChoiceClickListener() {@Overridepublic void onClick(DialogInterface dialogInterface, int i, boolean b) {Toast.makeText(getApplicationContext(),"You clicked "+items[i]+" "+b,Toast.LENGTH_SHORT).show();}});builder.setCancelable(true);AlertDialog dialog=builder.create();dialog.show();}
实现效果:
5,showCustomAdapterDialog()
:
这部分涉及到自定义Adapter,如果对这部分不太了解,也不用灰心,在后面的文章中我会单独讲解Adapter这部分。在这里我们只需要了解自定义Adapter需要继承自BaseAdapter,然后需要覆写其中四个方法,其中getView()方法负责显示,所以我们还需要为它创建一个布局文件:
layout->custom_adapter.xml
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:orientation="horizontal"android:background="#dddddd"android:layout_marginLeft="15dp"android:layout_marginTop="15dp"android:layout_marginBottom="10dp"android:layout_marginRight="15dp"android:layout_width="match_parent"android:layout_height="wrap_content"><ImageView
android:id="@+id/id_image"android:layout_width="60dp"android:layout_height="60dp" /><TextView
android:textColor="#554995"android:id="@+id/id_text"android:layout_marginLeft="20dp"android:layout_gravity="center"android:layout_width="wrap_content"android:layout_height="wrap_content" />
</LinearLayout>
布局效果:
然后我们在需要在MainActivity.java
中实现我们自定义的Adapter
类:
private class CustomAdapter extends BaseAdapter {private List<ItemBean> items;private LayoutInflater inflater;private ImageView image;private TextView text;public CustomAdapter(List<ItemBean> items, Context context) {this.items = items;this.inflater = LayoutInflater.from(context);}@Overridepublic int getCount() {return items.size();}@Overridepublic Object getItem(int i) {return items.get(i);}@Overridepublic long getItemId(int i) {return i;}@Overridepublic View getView(int i, View view, ViewGroup viewGroup) {if(view==null){view=inflater.inflate(R.layout.custom_adapter,null);image= (ImageView) view.findViewById(R.id.id_image);text= (TextView) view.findViewById(R.id.id_text);}image.setImageResource(items.get(i).getImageId());text.setText(items.get(i).getMessage());return view;}}
我们在这里使用了List items;是因为Adapter中需要一张图片和String来填充我们刚定义好的layout;所以我们还需要在MainActivity中建立一个数据类:ItemBean:
private class ItemBean{private int imageId;private String message;public ItemBean(int imageId, String message) {this.imageId = imageId;this.message = message;}public String getMessage() {return message;}public int getImageId() {return imageId;}public void setImageId(int imageId) {this.imageId = imageId;}public void setMessage(String message) {this.message = message;}}private void showCustomAdapterDialog(View view){builder=new AlertDialog.Builder(this);builder.setIcon(R.mipmap.ic_launcher);builder.setTitle(R.string.custom_adapter_dialog);/*** 设置内容区域为自定义adapter*/List<ItemBean> items=new ArrayList<>();items.add(new ItemBean(R.mipmap.icon,"You can call me xiaoming"));items.add(new ItemBean(R.mipmap.ic_launcher, "I'm android xiao"));CustomAdapter adapter=new CustomAdapter(items,getApplicationContext());builder.setAdapter(adapter, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialogInterface, int i) {Toast.makeText(getApplicationContext(),"You clicked"+i,Toast.LENGTH_SHORT).show();}});builder.setCancelable(true);AlertDialog dialog=builder.create();dialog.show();}
实现效果:
6,showCustomViewDialog()
为了实现自定义View的内容区域,我们首先需要建立一个布局文件:
layout->custom_view.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:orientation="vertical"android:gravity="center"android:background="#25AE90"><LinearLayout
android:orientation="horizontal"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginRight="60dp"android:layout_marginLeft="60dp"><TextView
android:text="用户名"android:layout_marginRight="10dp"android:textSize="20sp"android:textColor="#ffffff"android:layout_width="wrap_content"android:layout_height="wrap_content" /><EditText
android:layout_width="0dp"android:layout_weight="1"android:layout_height="40dp"android:background="#ffffff"/></LinearLayout><LinearLayout
android:orientation="horizontal"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="10dp"android:layout_marginRight="60dp"android:layout_marginLeft="60dp"><TextView
android:text="密 码"android:layout_marginRight="10dp"android:textSize="20sp"android:textColor="#ffffff"android:layout_width="wrap_content"android:layout_height="wrap_content" /><EditText
android:layout_width="0dp"android:layout_weight="1"android:layout_height="40dp"android:background="#ffffff"/></LinearLayout><LinearLayout
android:orientation="horizontal"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="10dp"android:layout_marginRight="60dp"android:layout_marginLeft="60dp"><Button
android:text="登 录"android:textColor="#25AE90"android:background="#ECEEF1"android:layout_width="0dp"android:layout_marginRight="10dp"android:layout_weight="1"android:layout_height="wrap_content" /><Button
android:text="取 消"android:textColor="#25AE90"android:background="#ECEEF1"android:layout_width="0dp"android:layout_weight="1"android:layout_height="wrap_content" /></LinearLayout>
</LinearLayout>
布局效果:
实现showCustomViewDialog()
private void showCustomViewDialog(View view){builder=new AlertDialog.Builder(this);builder.setIcon(R.mipmap.ic_launcher);builder.setTitle(R.string.custom_view_dialog);/*** 设置内容区域为自定义View*/LinearLayout loginDialog= (LinearLayout) getLayoutInflater().inflate(R.layout.custom_view,null);builder.setView(loginDialog);builder.setCancelable(true);AlertDialog dialog=builder.create();dialog.show();}
实现效果:
总结:
- AlertDialog基本用法 :需要掌握AlertDialog的创建过程,理解Builder模式;
- 内容区域 :AlertDialog的难点就在于设计合适的内容区域;
- 自定义布局 :很多时候我们都需要按照自己的意愿去定制AlertDialog内容区域的显示形式,这就需要我们掌握自定义Adapter和自定义View的用法,而这两部分也是一个难点,要讲的话又是另一个专题了;
作为文章的结束;为了检验我们是否已经掌握了AlertDialog的各种用法,我们可以试着实现以下微信中的AlertDialog;如果你已经掌握了自定义adapter和自定义ListView的话可以试着实现删除和置顶ListItem的功能。
Tips:编写自定义ListView,监听长按ListItem时弹出AlertDialog,并且实现点击删除能保证ListView中的Item删除掉,并且能够实现置顶功能
- 微博:@JueYingCoder,
- 个人主页:Coder:程序员&&工科男的日常,
Android常用实例—Alert Dialog的使用相关推荐
- 【转】 Android常用实例—Alert Dialog的使用
Android常用实例-Alert Dialog的使用 AlertDialog的使用很普遍,在应用中当你想要用户做出"是"或"否"或者其它各式各样的选择时,为了 ...
- Android常用实例——截取APP当前界面(可带图片、文字水印)
Android常用实例--截取APP当前界面(可带图片.文字水印) 标签: android界面截图保存图片 2016-08-16 10:52 1262人阅读 评论(2) 收藏 举报 分类: Andr ...
- Android 常用设计模式
原文:Common Design Patterns for Android 作者:Matt Luedke 译者:kmyhy 除了让你的客户和老板满意,对于一名开发者来说,还有一件更重要的东西能够让你保 ...
- Android常用开源项目
Android开源项目第一篇--个性化控件(View)篇 包括ListView.ActionBar.Menu.ViewPager.Gallery.GridView.ImageView.Progre ...
- Android常用面试题大全
1.TCP和UDP之间的区别?什么是URL ? TCP被称为用户数据报协议;UDP被称为信息传输控制协议;URL被称为统一资源定位符,通过统一资源定位符可以唯一定位到互联网上的某个资源(图片.视频.音 ...
- android 常用框架整理
文章目录 UI 框架 WebView 框架 具体内容 UI 卫星菜单 节选器 下拉刷新 模糊效果 HUD与Toast 进度条 UI其他 动画 网络相关 网络连接 网络测试 图像获取 响应式编程 地图 ...
- Android应用Activity、Dialog、PopWindow、Toast窗口添加机制及源码分析
1 背景 之所以写这一篇博客的原因是因为之前有写过一篇<Android应用setContentView与LayoutInflater加载解析机制源码分析>, 然后有人在文章下面评论和微博 ...
- Android常用酷炫控件(开源项目)github地址汇总
转载一个很牛逼的控件收集帖... 第一部分 个性化控件(View) 主要介绍那些不错个性化的 View,包括 ListView.ActionBar.Menu.ViewPager.Gallery.Gri ...
- Android常用开源库种类大全
## 1.基本控件 ### [](https://www.yundashi168.com/articles/2018/09/12/1536725366888.html#11textview)1.1.T ...
最新文章
- ssh-keys git
- linux查找文件命令 要查找包含某字符
- mfc程序转化为qt_10年程序员:我都学过这些语言,2019年开始我再也不是程序员......
- Node.js与网络:Node.js对TCP、UDP、Socket、HTTP等协议的实现和支持
- 机器学习实战(三)朴素贝叶斯NB(Naive Bayes)
- 百度编辑器 ueditor .net开发
- 吊炸天!15岁成杀人犯,监狱里学编程,37岁获释后年薪70万
- 怎样在photoshop中快速批量,修改图片
- 【胸片分割】基于matlab GUI最小误差法胸片分割系统【含Matlab源码 1065期】
- PostScript 打印描述语言 介绍
- 伺服电机负载惯量比的合理取值
- word里如何设置目录页码
- 获取UI控件位置信息
- 有些路,只能一个人走。
- 彻底带你入门RDS数据库「玩转华为云」
- linux系统防篡改,网站防篡改脚本
- cad零点坐标标注lisp_CAD_XY坐标标注AUTO_LISP程序
- 中学生读以奋斗者为本有感3500字
- 批处理删除重复的文件
- 【人工智能】1024 程序员节最想要的大礼包!