AlertDialog使用

要创建一个对话框,我们需要做些什么

可以将对话框主要分为三个部分:
上面区域是标题栏和图标
中间区域是内容区
下方是button区

其他形式各异的对话框也都是基于此的变体而已

1、首先需要创建一个AlertDialog.Builder对象,基本语法:

AlertDialog.Builder alertDialogBuilder=new AlertDialog.Builder(this);

2、通过调用它的create()方法就可以构造出一个对话框

AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();//将dialog显示出来

3、通过调用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

这里写图片描述

关键代码

private void showNormalDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(R.mipmap.ic_launcher);
        builder.setTitle(R.string.simpleDialogTitle);
        builder.setMessage(R.string.simpleDialogMessage);

        //button监听
        builder.setPositiveButton(R.string.confirmButton, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(getApplicationContext(),"您点击了确定按钮",Toast.LENGTH_SHORT).show();
            }
        });

        builder.setNegativeButton(R.string.cancelButton, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(getApplicationContext(),"您点击了取消按钮",Toast.LENGTH_SHORT).show();
            }
        });

        //设置对话框是可取消的
        builder.setCancelable(true);

        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

简单列表Dialog

这里写图片描述

关键代码

 private void showNormalItemDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(R.mipmap.ic_launcher);
        builder.setTitle(R.string.simpleDialogTitle);

        final String[] items = {"Item one","Item two","Item three"};

        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(getApplicationContext(),"You clicked "+items[i],Toast.LENGTH_SHORT).show();
            }
        });
        //设置对话框是可取消的
        builder.setCancelable(true);

        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

单选列表Dialog

这里写图片描述

关键代码

    private void showSingleChoiceItemDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(R.mipmap.ic_launcher);
        builder.setTitle(R.string.singleChoiceItemTitle);

        final String[] items = {"Item one","Item two","Item three"};

        builder.setSingleChoiceItems(items, 1, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                Toast.makeText(getApplicationContext(), "You clicked "+items[i], Toast.LENGTH_SHORT).show();
            }
        });
        builder.setCancelable(true);

        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

多选列表Dialog

这里写图片描述

关键代码

private void showMultiChoiceItemDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setIcon(R.mipmap.ic_launcher);
        builder.setTitle(R.string.multiChoiceItemTitle);

        final String[] items = {"Item one","Item two","Item three"};

        builder.setMultiChoiceItems(items, new boolean[]{true, true, false}, new DialogInterface.OnMultiChoiceClickListener() {


            @Override
            public void onClick(DialogInterface dialogInterface, int i, boolean b) {
                Toast.makeText(getApplicationContext(),"You clicked "+items[i]+" "+b,Toast.LENGTH_SHORT).show();
            }
        });
        builder.setCancelable(true);

        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

自定义布局Dialog

这里写图片描述

先自定义一个布局

dialog_forward_type.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="wrap_content"
              android:orientation="vertical"
              android:gravity="center">

    <TextView
        android:id="@+id/dialog_forward_type_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="请选择转发类型"/>

    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#dddddd"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="20dp">

        <LinearLayout
            android:id="@+id/dialog_forward_video_layout"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:gravity="center"
            android:layout_weight="1">
            <ImageView
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:src="@mipmap/btn_forward_video"
                />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="视频"
                android:layout_marginTop="10dp"/>
        </LinearLayout>

        <LinearLayout
            android:id="@+id/dialog_forward_image_layout"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:orientation="vertical"
            android:gravity="center"
            android:layout_weight="1">

            <ImageView
                android:layout_width="50dp"
                android:layout_height="50dp"
                android:src="@mipmap/btn_forward_images"
                />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="图片"
                android:layout_marginTop="10dp"/>
        </LinearLayout>

    </LinearLayout>

</LinearLayout>

关键代码

    private void showCustomDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        LinearLayout layout = (LinearLayout)getLayoutInflater().inflate(R.layout.dialog_forward_type,null);
        builder.setView(layout);

        LinearLayout videoLayout = (LinearLayout)layout.findViewById(R.id.dialog_forward_video_layout);
        LinearLayout imageLayout = (LinearLayout)layout.findViewById(R.id.dialog_forward_image_layout);

        videoLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(),"U clicked Video type",Toast.LENGTH_SHORT).show();
            }
        });
        imageLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(),"U clicked Image type",Toast.LENGTH_SHORT).show();
            }
        });

        builder.setCancelable(true);
        AlertDialog alertDialog = builder.create();
        alertDialog.show();
    }

优化

点击按钮每一次都会创建一个新的对话框其实是没有必要的,对于这种没有必要每次创建的对话框,可以在一开始就创建好,然后点击时显示就可以了。

我们可以将第一个 简单 Dialog 改为:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button button;
    private AlertDialog dialog;

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

        button = findViewById(R.id.button);
        button.setOnClickListener(this);

        initDialog();
    }

    private void initDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        ......

        //设置对话框是可取消的
        builder.setCancelable(true);
		dialog = builder.create();
    }

    @Override
    public void onClick(View v) {
        dialog.show();
    }
}

另外,builder.set方法是有返回值的,返回的就是 builder。因此创建 AlertDialog 也可以写成:

       new AlertDialog.Builder(this)
                .setIcon(R.mipmap.ic_launcher)
                .setTitle("警告")
                .setMessage("你确定明天不来学校吗?")
                .setPositiveButton("确定", null)
                .setNeutralButton("随便", null)
                .setNegativeButton("取消", null)
                .setCancelable(false)
                .create()
                .show();

推荐写法

        AlertDialog dialog = new AlertDialog.Builder(this)
                .setIcon(R.mipmap.ic_launcher)
                .setTitle("警告")
                .setMessage("你确定明天不来学校吗?")
                .setPositiveButton("确定", null)
                .setNeutralButton("随便", null)
                .setNegativeButton("取消", null)
                .setCancelable(false)
                .create();

        dialog.show();

可能遇到的问题

设置宽高、背景不管用

dialog 根布局已经设置了宽高背景,但是不起作用,可以在根布局再加一层 RelativeLayout,如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#A5000000"
    android:gravity="center">
	//在这中间写原来Dialog布局
	//根布局 RelativeLayout 背景是必须的,否则不起作用,不知为何
</RelativeLayout>

这样宽高、背景就都起作用了

如果只是想限定宽高,可以不加以上布局,直接在 dialog.show() 之后,加上以下代码设置宽高

			Window window = alertDialog.getWindow();
            WindowManager.LayoutParams lp = window.getAttributes();
            lp.gravity = Gravity.CENTER;
            lp.width = (int) AppUtils.convertDpToPixel(320);//dp转px方法,自己写即可
            lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
            alertDialog.getWindow().setAttributes(lp);

Demo源码下载

戳这里下载源码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值