Android中的AlertDialog(警告对话框)

大道之行,天下为公。这篇文章主要讲述Android中的AlertDialog(警告对话框)相关的知识,希望能为你提供帮助。
【Android中的AlertDialog(警告对话框)】在android开发中,我们经常会需要在Android界面上弹出一些对话框,比如询问用户或者让用户选择。这些功能我们叫它Android Dialog对话框,AlertDialog实现方法为建造者模式。下面我们模拟卸载应用程序时弹出的最为普通的警告对话框,如下图:

Android中的AlertDialog(警告对话框)

文章图片

layout布局界面代码示例:
1 < ?xml version="1.0" encoding="utf-8"?> 2 < LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 3android:orientation="vertical" android:layout_width="match_parent" 4android:layout_height="match_parent"> 5< Button 6android:text="卸载" 7android:layout_width="match_parent" 8android:layout_height="wrap_content" 9android:onClick="show" 10android:id="@+id/button" /> 11 < /LinearLayout>

Java实现代码:
1 import android.content.DialogInterface; 2 import android.os.Bundle; 3 import android.support.annotation.Nullable; 4 import android.support.v7.app.AlertDialog; 5 import android.support.v7.app.AppCompatActivity; 6 import android.view.View; 7 import android.widget.Toast; 8 /** 9* Created by panchengjia on 2016/11/21. 10*/ 11 public class AlertDialogDemo extends AppCompatActivity { 12@Override 13protected void onCreate(@Nullable Bundle savedInstanceState) { 14super.onCreate(savedInstanceState); 15setContentView(R.layout.alterdialog); 16} 17public void show(View v){ 18//实例化建造者 19AlertDialog.Builder builder = new AlertDialog.Builder(this); 20//设置警告对话框的标题 21builder.setTitle("卸载"); 22//设置警告显示的图片 23 //builder.setIcon(android.R.drawable.ic_dialog_alert); 24//设置警告对话框的提示信息 25builder.setMessage("确定卸载吗"); 26//设置”正面”按钮,及点击事件 27builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { 28@Override 29public void onClick(DialogInterface dialog, int which) { 30Toast.makeText(AlertDialogDemo.this,"点击了确定按钮",Toast.LENGTH_SHORT).show(); 31} 32}); 33//设置“反面”按钮,及点击事件 34builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { 35@Override 36public void onClick(DialogInterface dialog, int which) { 37Toast.makeText(AlertDialogDemo.this,"点击了取消按钮",Toast.LENGTH_SHORT).show(); 38} 39}); 40//设置“中立”按钮,及点击事件 41builder.setNeutralButton("等等看吧", new DialogInterface.OnClickListener() { 42@Override 43public void onClick(DialogInterface dialog, int which) { 44Toast.makeText(AlertDialogDemo.this,"点击了中立按钮",Toast.LENGTH_SHORT).show(); 45} 46}); 47//显示对话框 48builder.show(); 49} 50 }

 

    推荐阅读