android AlertDialog 详解

1 效果图

先看效果图:


2 概述

AlertDialog生成的对话框可分为4个区域:图标区,标题区,内容区,按钮区

结构如图:

AlertDialog的构造方法全部是Protected的,所以不能直接通过new一个AlertDialog来创建出一个AlertDialog。要创建一个AlertDialog,就要用到AlertDialog.Builder中的create()方法。

AlertDialog对话框的使用步骤:

1,创建AlertDialog.Builder对象

2,调用Builder对象的setTitle()设置标题,setIcon设置图标

3,调用Builder对象的相关方法设置内容,AlertDialog提供如下设置指定对话框的内容:

setMessage();设置简单文本框的内容

setItems();设置简单列表的内容,数组

setSingleChoiceItems();;设置单选列表的内容,内容参数可以是数组Cursor,ListAdapter

setMultiChoiceItems();设置多选列表项的内容,内容参数可以是数组,Cursor

setAdapter();设置内容,内容是ListAdapter,常用的BaseAdapter,SimpleAdapter,ArrayAdapter

setView();设置内容,参数是自定义的View

setItems :设置对话框要显示的一个list,一般用于显示几个命令时 

4,调用Builder对象的setPositiveButton()和 setNegativeButton()设置按钮和监听器

5,调用Builder对象的create()方法创建AlertDialog对象,再调用AlertDialog对象的show()方法显示对话框

总之:调用Builder对象设置图标,标题,内容,按钮,在create(),show()

2 概述

3 例子代码

java代码

package mm.shandong.com.testalertdialog;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Toast;

import java.lang.reflect.Field;
import java.util.ArrayList;

public class TestAlertDialogActivity extends AppCompatActivity {
    String nav_name = "AlertDialog";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_alert_dialog);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setTitle(nav_name + " demo");
    }

    ///显示普通对话框
    public void showNomalDialog(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("普通对话框");
        builder.setIcon(R.drawable.head1);
        builder.setMessage("对话框文本内容");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(TestAlertDialogActivity.this,
                        "您点击的是确定按钮",
                        Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(TestAlertDialogActivity.this,
                        "您点击的是取消按钮",
                        Toast.LENGTH_SHORT).show();
            }
        });
        builder.create().show();
    }

    显示列表对话框
    public void showListDialog(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("列表对话框");
        builder.setIcon(R.drawable.head2);
        final String[] arrayRegion = getResources().
                getStringArray(R.array.arrayRegion);
        builder.setItems(arrayRegion, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int position) {

                Toast.makeText(TestAlertDialogActivity.this,
                        arrayRegion[position], Toast.LENGTH_SHORT).show();
            }
        });

        builder.create().show();
    }

    ///显示有单选按钮的对话框
    public void showSingleListDialog(View view) {
        final AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("单选列表对话框");
        builder.setIcon(R.drawable.head2);
        final String[] arrayRegion = getResources().getStringArray(R.array.arrayRegion);
        builder.setSingleChoiceItems(arrayRegion,1,
          new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int position) {
                Toast.makeText(TestAlertDialogActivity.this,
                        arrayRegion[position], Toast.LENGTH_SHORT).show();
            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                AlertDialog alertDialog = (AlertDialog) dialogInterface;
                int sp = alertDialog.getListView().getCheckedItemPosition();
                String str = (String) alertDialog.getListView().getItemAtPosition(sp);

                Toast.makeText(TestAlertDialogActivity.this,
                        str, Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(TestAlertDialogActivity.this,
                        "您点击的是取消按钮", Toast.LENGTH_SHORT).show();
            }
        });
        builder.create().show();
    }

    ///显示有多选按钮的对话框
    public void showMultiListDialog(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("多选列表对话框");
        builder.setIcon(R.drawable.head2);
        final String[] arrayRegion = getResources().getStringArray(R.array.arrayRegion);
        final boolean[] selectItems = new boolean[arrayRegion.length];
        for (int i = 0; i < arrayRegion.length; i++) {
            selectItems[i] = false;
        }
        builder.setMultiChoiceItems(arrayRegion, selectItems,
          new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i,boolean b) {

            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int position) {
                String str = "";
                for (int i = 0; i < arrayRegion.length; i++) {
                    if (selectItems[i]) {
                        str += arrayRegion[i] + " ";
                    }
                }
                Toast.makeText(TestAlertDialogActivity.this, str,
                        Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(TestAlertDialogActivity.this,
                        "您点击的是取消按钮", Toast.LENGTH_SHORT).show();
            }
        });
        builder.create().show();
    }

    ///显示设置arrayAdpater的对话框
    public void showAdapterListDialog(View view) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Adapter对话框");
        builder.setIcon(R.drawable.head2);
        final String[] arrayRegion = getResources().
                getStringArray(R.array.arrayRegion);
        ArrayAdapter arrayAdapter = new ArrayAdapter(this,
                android.R.layout.simple_list_item_1, arrayRegion);
        builder.setAdapter(arrayAdapter, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {

            }
        });

        builder.create().show();
    }

    ///显示自定义view的对话框
    public void showViewDialog(View view) {
        View view2 = getLayoutInflater().
                inflate(R.layout.item_testalertdialog_alertdialog, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("自定义View对话框");
        builder.setIcon(R.drawable.head2);
        builder.setView(view2);

        builder.setPositiveButton("提交", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int position) {
                Toast.makeText(TestAlertDialogActivity.this,
                        "点击提交按钮", Toast.LENGTH_SHORT).show();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(TestAlertDialogActivity.this,
                        "您点击的是取消按钮", Toast.LENGTH_SHORT).show();
            }
        });
        builder.create().show();
    }

    ///显示对输入表单进行验证的对话框,如果不合法不允许关闭对话框
    public void showNoClosedDialog(View view) {
        View view2 = getLayoutInflater().
                inflate(R.layout.item_testalertdialog_alertdialog, null);
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("自定义View对话框");
        builder.setIcon(R.drawable.head2);
        builder.setView(view2);
        final EditText et_name = (EditText) view2.findViewById(R.id.et_name);
        final EditText et_phone = (EditText) view2.findViewById(R.id.et_phone);
        builder.setPositiveButton("提交", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int position) {
                AlertDialog alertDialog = (AlertDialog) dialogInterface;
                Field field = null;
                try {
                    field = dialogInterface.getClass().
                            getSuperclass().getDeclaredField("mShowing");
                    field.setAccessible(true);
                    field.set(dialogInterface, false);


                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (TextUtils.isEmpty(et_name.getText().toString()) ||
                        TextUtils.isEmpty(et_phone.getText().toString())) {

                    Toast.makeText(TestAlertDialogActivity.this,
                            "姓名或手机号不能为空", Toast.LENGTH_SHORT).show();
                } else {
                    try {
                        field.set(dialogInterface, true);
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }

                    //     dialogInterface.dismiss();
                }


            }
        });

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Field field = null;
                try {
                    field = dialogInterface.getClass().getSuperclass().
                            getDeclaredField("mShowing");
                    field.setAccessible(true);
                    field.set(dialogInterface, true);
                    dialogInterface.dismiss();
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        });
        builder.create().show();
    }


}
主界面布局文件

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="showNomalDialog"
        android:text="普通对话框" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="showListDialog"
        android:text="简单列表对话框" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="showSingleListDialog"
        android:text="单选列表对话框" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="showMultiListDialog"
        android:text="多选列表对话框" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="showAdapterListDialog"
        android:text="Adapter列表对话框" />
    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="showViewDialog"
        android:text="自定义View对话框" />


    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:onClick="showNoClosedDialog"
        android:text="点击确定按钮不关闭对话框" />
</LinearLayout>

自定义对话框view布局文件

<?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">

    <TableLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:stretchColumns="1">
        <TableRow>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="用户名"
                android:textSize="17sp" />
            <EditText
                android:id="@+id/et_name"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:hint="请输入用户名"
                android:selectAllOnFocus="true"
                android:textColorHint="#238745" />
        </TableRow>
        <TableRow>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="密码"
                android:textSize="17sp" />
            <EditText
                android:id="@+id/et_password"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:hint="请输入密码"
                android:inputType="textPassword"
                android:selectAllOnFocus="true" />
        </TableRow>
        <TableRow>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="年龄"
                android:textSize="17sp" />
            <EditText
                android:id="@+id/et_age"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:hint="请输入年龄"
                android:inputType="number"
                android:selectAllOnFocus="true" />
        </TableRow>
        <TableRow>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="生日"
                android:textSize="17sp" />
            <EditText
                android:id="@+id/et_birthday"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:hint="请输入生日"
                android:inputType="date"
                android:selectAllOnFocus="true" />
        </TableRow>
        <TableRow>
            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="手机"
                android:textSize="17sp" />
            <EditText
                android:id="@+id/et_phone"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:hint="请输入手机号"
                android:inputType="phone"
                android:selectAllOnFocus="true" />
        </TableRow>
    </TableLayout>
</LinearLayout>

4 Demo下载

本人微博:honey_11

最后,以上例子都来源与安卓无忧,请去应用宝或者豌豆荚下载:源码下载,源码例子文档一网打尽。例子源码,百度网盘地址:

http://pan.baidu.com/s/1cn7v58


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值