【安卓组件】Dialog的八种使用方式

【安卓组件】Dialog的八种使用方式
这里我们实现八种dialog 在一个页面定义9个按钮,给每个按钮绑定单击事件。

目录结构 【安卓组件】Dialog的八种使用方式

布局代码:

<?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:gravity="center"
    android:orientation="vertical"
    android:padding="10dp"
    tools:context=".MainActivity">


    <Button
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:onClick="showNormalDialog"
        android:text="@string/NormalDialog" />

    <Button
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:onClick="showMultiBtnDialog"
        android:text="@string/MultiBtnDialog" />

    <Button
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:onClick="showListDialog"
        android:text="@string/ListDialog" />

    <Button
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:onClick="showSingleChoiceDialog"
        android:text="@string/SingleChoiceDialog" />

    <Button
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:onClick="showMultiChoiceDialog"
        android:text="@string/MultiChoiceDialog" />

    <Button
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:onClick="showWaitingDialog"
        android:text="@string/WaitingDialog" />

    <Button
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:onClick="showProgressDialog"
        android:text="@string/ProgressDialog" />

    <Button
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:onClick="showInputDialog"
        android:text="@string/InputDialog" />

    <Button
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:onClick="showCustomizeDialog"
        android:text="@string/CustomizeDialog" />

</LinearLayout>

主类代码:

package com.example.a15114.dialog;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

    }


    /**
     * 简单dialog 2个按钮
     * @param view
     */
    public void showNormalDialog(View view) {
        final android.support.v7.app.AlertDialog.Builder normalDialog =
                new android.support.v7.app.AlertDialog.Builder(MainActivity.this);
        normalDialog.setIcon(R.mipmap.ic_launcher);
        normalDialog.setTitle("我是一个普通Dialog");
        normalDialog.setMessage("你要点击哪一个按钮呢?");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                    }
                });
        normalDialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //...To-do
                    }
                });
        // 显示
        normalDialog.show();
    }

    /**
     * 简单dialog 3个按钮
     * @param view
     */
    public void showMultiBtnDialog(View view) {
        AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(MainActivity.this);
        normalDialog.setIcon(R.mipmap.ic_launcher);
        normalDialog.setTitle("我是一个普通Dialog").setMessage("你要点击哪一个按钮呢?");
        normalDialog.setPositiveButton("按钮1",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // ...To-do
                    }
                });
        normalDialog.setNeutralButton("按钮2",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // ...To-do
                    }
                });
        normalDialog.setNegativeButton("按钮3", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // ...To-do
            }
        });
        // 创建实例并显示
        normalDialog.show();
    }

    /**
     * 列表dialog
     * @param view
     */
    public void showListDialog(View view) {
        final String[] items = { "我是1","我是2","我是3","我是4" };
        AlertDialog.Builder listDialog =
                new AlertDialog.Builder(MainActivity.this);
        listDialog.setTitle("我是一个列表Dialog");
        listDialog.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // which 下标从0开始
                // ...To-do
                Toast.makeText(MainActivity.this,
                        "你点击了" + items[which],
                        Toast.LENGTH_SHORT).show();
            }
        });
        listDialog.show();
    }

    /**
     * 单选dialog
     * @param view
     */
    int yourChoice;
    public void showSingleChoiceDialog(View view) {
        final String[] items = { "我是1","我是2","我是3","我是4" };
        yourChoice = -1;
        AlertDialog.Builder singleChoiceDialog =
                new AlertDialog.Builder(MainActivity.this);
        singleChoiceDialog.setTitle("我是一个单选Dialog");
        // 第二个参数是默认选项,此处设置为0
        singleChoiceDialog.setSingleChoiceItems(items, 0,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        yourChoice = which;
                    }
                });
        singleChoiceDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (yourChoice != -1) {
                            Toast.makeText(MainActivity.this,
                                    "你选择了" + items[yourChoice],
                                    Toast.LENGTH_SHORT).show();
                        }
                    }
                });
        singleChoiceDialog.show();
    }

    /**
     * 多选dialog
     * @param view
     */
    ArrayList<Integer> yourChoices = new ArrayList<>();
    public void showMultiChoiceDialog(View view) {
        final String[] items = { "我是1","我是2","我是3","我是4" };
        // 设置默认选中的选项,全为false默认均未选中
        final boolean initChoiceSets[]={false,false,false,false};
        yourChoices.clear();
        AlertDialog.Builder multiChoiceDialog =
                new AlertDialog.Builder(MainActivity.this);
        multiChoiceDialog.setTitle("我是一个多选Dialog");
        multiChoiceDialog.setMultiChoiceItems(items, initChoiceSets,
                new DialogInterface.OnMultiChoiceClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which,
                                        boolean isChecked) {
                        if (isChecked) {
                            yourChoices.add(which);
                        } else {
                            yourChoices.remove(which);
                        }
                    }
                });
        multiChoiceDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        int size = yourChoices.size();
                        String str = "";
                        for (int i = 0; i < size; i++) {
                            str += items[yourChoices.get(i)] + " ";
                        }
                        Toast.makeText(MainActivity.this,
                                "你选中了" + str,
                                Toast.LENGTH_SHORT).show();
                    }
                });
        multiChoiceDialog.show();
    }

    /**
     * 等待dialog
     * @param view
     */
    public void showWaitingDialog(View view) {
        /* 等待Dialog具有屏蔽其他控件的交互能力
         * @setCancelable 为使屏幕不可点击,设置为不可取消(false)
         * 下载等事件完成后,主动调用函数关闭该Dialog
         */
        ProgressDialog waitingDialog=
                new ProgressDialog(MainActivity.this);
        waitingDialog.setTitle("我是一个等待Dialog");
        waitingDialog.setMessage("等待中...");
        waitingDialog.setIndeterminate(true);
        waitingDialog.setCancelable(false);
        waitingDialog.show();
    }

    /**
     * 进度条dialog
     * @param view
     */
    public void showProgressDialog(View view) {
        /* @setProgress 设置初始进度
         * @setProgressStyle 设置样式(水平进度条)
         * @setMax 设置进度最大值
         */
        final int MAX_PROGRESS = 100;
        final ProgressDialog progressDialog =
                new ProgressDialog(MainActivity.this);
        progressDialog.setProgress(0);
        progressDialog.setTitle("我是一个进度条Dialog");
        progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        progressDialog.setMax(MAX_PROGRESS);
        progressDialog.show();
        /* 模拟进度增加的过程
         * 新开一个线程,每个100ms,进度增加1
         */
        new Thread(new Runnable() {
            @Override
            public void run() {
                int progress= 0;
                while (progress < MAX_PROGRESS){
                    try {
                        Thread.sleep(100);
                        progress++;
                        progressDialog.setProgress(progress);
                    } catch (InterruptedException e){
                        e.printStackTrace();
                    }
                }
                // 进度达到最大值后,窗口消失
                progressDialog.cancel();
            }
        }).start();
    }

    /**
     *编辑dialog
     * @param view
     */
    public void showInputDialog(View view) {
        /*@setView 装入一个EditView
         */
        final EditText editText = new EditText(MainActivity.this);
        AlertDialog.Builder inputDialog =
                new AlertDialog.Builder(MainActivity.this);
        inputDialog.setTitle("我是一个输入Dialog").setView(editText);
        inputDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(MainActivity.this,
                                editText.getText().toString(),
                                Toast.LENGTH_SHORT).show();
                    }
                }).show();
    }

    /**
     * 自定义dialog
     * @param view
     */
    public void showCustomizeDialog(View view) {
        /* @setView 装入自定义View ==> R.layout.dialog_customize
         * 由于dialog_customize.xml只放置了一个EditView,因此和图8一样
         * dialog_customize.xml可自定义更复杂的View
         */
        AlertDialog.Builder customizeDialog =
                new AlertDialog.Builder(MainActivity.this);
        final View dialogView = LayoutInflater.from(MainActivity.this)
                .inflate(R.layout.dialog_customize,null);
        customizeDialog.setTitle("我是一个自定义Dialog");
        customizeDialog.setView(dialogView);
        customizeDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // 获取EditView中的输入内容
                        EditText edit_text =
                                (EditText) dialogView.findViewById(R.id.edit_text);
                        Toast.makeText(MainActivity.this,
                                edit_text.getText().toString(),
                                Toast.LENGTH_SHORT).show();
                    }
                });
        customizeDialog.show();
    }


   /* *//* 复写Builder的create和show函数,可以在Dialog显示前实现必要设置
     * 例如初始化列表、默认选项等
     * @create 第一次创建时调用
     * @show 每次显示时调用
     *//*
    private void showListDialog() {
        final String[] items = { "我是1","我是2","我是3","我是4" };
        AlertDialog.Builder listDialog =
                new AlertDialog.Builder(MainActivity.this){

                    @Override
                    public AlertDialog create() {
                        items[0] = "我是No.1";
                        return super.create();
                    }

                    @Override
                    public AlertDialog show() {
                        items[1] = "我是No.2";
                        return super.show();
                    }
                };
        listDialog.setTitle("我是一个列表Dialog");
        listDialog.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // ...To-do
            }
        });
        *//* @setOnDismissListener Dialog销毁时调用
         * @setOnCancelListener Dialog关闭时调用
         *//*
        listDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            public void onDismiss(DialogInterface dialog) {
                Toast.makeText(getApplicationContext(),
                        "Dialog被销毁了",
                        Toast.LENGTH_SHORT).show();
            }
        });
        listDialog.show();
    }*/
}

string资源:

<resources>
    <string name="app_name">Dialog</string>
    <string name="NormalDialog">普通Dialog</string>
    <string name="MultiBtnDialog">三按钮Dialog</string>
    <string name="ListDialog">列表Dialog</string>
    <string name="SingleChoiceDialog">单选Dialog</string>
    <string name="MultiChoiceDialog">多选Dialog</string>
    <string name="WaitingDialog">等待Dialog</string>
    <string name="ProgressDialog">进度条Dialog</string>
    <string name="InputDialog">编辑Dialog</string>
    <string name="CustomizeDialog">自定义Dialog</string>
</resources>

自定义弹窗的布局:dialog_customize.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">
    <EditText
        android:id="@+id/edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
</LinearLayout>

以后更新的这个【安卓组件】系列都是开发中会经常用到的,需要用时来复制粘贴节省很多时间,感谢各位能停留下来观看我的博文。