Android中的AlertDialog使用示例一(警告对话框)

在Android开发中,我们经常会需要在Android界面上弹出一些对话框,比如询问用户或者让用户选择。这些功能我们叫它Android Dialog对话框,AlertDialog实现方法为建造者模式。下面我们模拟卸载应用程序时弹出的最为普通的警告对话框,如下图:

layout布局界面代码示例:

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:orientation="vertical" android:layout_width="match_parent"
 4     android:layout_height="match_parent">
 5     <Button
 6         android:text="卸载"
 7         android:layout_width="match_parent"
 8         android:layout_height="wrap_content"
 9         android:onClick="show"
10         android: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
13     protected void onCreate(@Nullable Bundle savedInstanceState) {
14         super.onCreate(savedInstanceState);
15         setContentView(R.layout.alterdialog);
16     }
17     public void show(View v){
18         //实例化建造者
19         AlertDialog.Builder builder = new AlertDialog.Builder(this);
20         //设置警告对话框的标题
21         builder.setTitle("卸载");
22         //设置警告显示的图片
23 //        builder.setIcon(android.R.drawable.ic_dialog_alert);
24         //设置警告对话框的提示信息
25         builder.setMessage("确定卸载吗");
26         //设置”正面”按钮,及点击事件
27         builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
28             @Override
29             public void onClick(DialogInterface dialog, int which) {
30                 Toast.makeText(AlertDialogDemo.this,"点击了确定按钮",Toast.LENGTH_SHORT).show();
31             }
32         });
33         //设置“反面”按钮,及点击事件
34         builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
35             @Override
36             public void onClick(DialogInterface dialog, int which) {
37                 Toast.makeText(AlertDialogDemo.this,"点击了取消按钮",Toast.LENGTH_SHORT).show();
38             }
39         });
40         //设置“中立”按钮,及点击事件
41         builder.setNeutralButton("等等看吧", new DialogInterface.OnClickListener() {
42             @Override
43             public void onClick(DialogInterface dialog, int which) {
44                 Toast.makeText(AlertDialogDemo.this,"点击了中立按钮",Toast.LENGTH_SHORT).show();
45             }
46         });
47         //显示对话框
48         builder.show();
49     }
50 }
原文地址:https://www.cnblogs.com/panhouye/p/6092144.html