AlertDialog对话框的几种实现方法,AlertDialog.Builder类

本文介绍了在Android开发中创建AlertDialog对象的两种方法。一是使用构建者模式,通过AlertDialog.Builder类的系列方法实现功能;二是创建自己的AlertDialog类并实例化对象。最后小结指出,自己创建的AlertDialog更灵活、布局更精确。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.构建者模式创建一个AlertDialog对象

构建者模式是Android开发的一种模式 .
大致的思路:
通过AlertDialog.Builder类创建一个对象,通过该类的方法实现一系列的功能.
AlertDialog.Builder类的常用方法:
1)public AlertDialog.Builder(Context context);
    创建AlertDialog.Builder的对象

2)public AlertDialog.Builder setTitle(CharSequence title);
    设置对话框的标题

3)public AlertDialog.Builder setMessage(CharSequence message);
    设置对话框的显示的信息

4)public AlertDialog.Builder setView(View view);
    对话框的内容为一个xml文件,即用xml布局对话框内容

5)public AlertDialog.Builder setPositiveButton(CharSequence text,OnClickListener listener);
    为对话框设置一个确定按钮,并监听该按钮

6)public AlertDialog.Builder setNegativeButton(CharSequence text,OnClickListener listener);
    为对话框设置一个取消按钮,并监听该按钮

7)public AlertDialog create ()必写
    用于真正创建AlertDialog.Builder类的对象

8)public AlertDialog show()
    用于显示AlertDialog对话框, 必写

我们根据需求可以用setMessage()方法设置对话框显示的内容,也可以用xml文件设置对话框要显示的内容,如下图所示:
在这里插入图片描述
Activity文件

package com.example.myapplication;

import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;

public class alertDialog extends AppCompatActivity implements View.OnClickListener {
    private Button btn_message,btn_xml;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alert_dialog);
        btn_message=(Button)findViewById(R.id.btn_message);
        btn_xml=(Button)findViewById(R.id.btn_xml);
        btn_message.setOnClickListener(this);
        btn_xml.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_message:
                showMessage();
                break;
            case R.id.btn_xml:
                showXml();
                break;
        }
    }

    private void showMessage() {
        AlertDialog alertDialog=new AlertDialog.Builder(this)
                .setTitle("警告框")
                .setMessage("您确定退出本程序吗?")//设置对话框显示的内容
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {//给对话框添加一个确定按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(alertDialog.this,"您已经退出本程序",Toast.LENGTH_LONG).show();
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {//给对话框添加一个否定按钮
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Toast.makeText(alertDialog.this,"恭喜您还在本程序中",Toast.LENGTH_LONG).show();
                    }
                })
                .create();
        alertDialog.show();
    }

    private void showXml() {
        final View view= LayoutInflater.from(this).inflate(R.layout.alertdialogxml,null);//将布局的xml文件转为View对象
        final RadioGroup radioGroup=view.findViewById(R.id.radio_group);
        radioGroup.check(R.id.rb_1);//为单选组设置默认选中
        AlertDialog alertDialog=new AlertDialog.Builder(this)
                .setTitle("请选择你喜欢的水果:")
                .setView(view)
                .setPositiveButton("提交", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                       RadioButton btn=(RadioButton)view.findViewById(radioGroup.getCheckedRadioButtonId());//获得被选中的按钮
                       String txt=btn.getText().toString();
                       Toast.makeText(alertDialog.this,"您选择的水果是:"+txt,Toast.LENGTH_LONG).show();

                    }
                })
                .setNeutralButton("重选", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        radioGroup.clearCheck();
                        Toast.makeText(alertDialog.this,"您进行了重选",Toast.LENGTH_LONG).show();
                    }
                })
                .create();
        alertDialog.show();
    }
}

Activity文件的布局文件          activity_alert_dialog.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".alertDialog">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <Button
            android:id="@+id/btn_message"
            android:layout_width="wrap_content"
            android:layout_marginLeft="30dp"
            android:textSize="22dp"
            android:textColor="#aaf"
            android:layout_height="wrap_content"
            android:text="用message设置对话框的内容"/>

        <Button
            android:id="@+id/btn_xml"
            android:layout_width="wrap_content"
            android:textSize="22dp"
            android:textColor="#aaf"
            android:layout_marginTop="10dp"
            android:layout_marginLeft="30dp"
            android:layout_height="wrap_content"
            android:text="用xml文件设置对话框的内容"/>
    </LinearLayout>

</android.support.constraint.ConstraintLayout>

对话框布局文件            alertdialogxml.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">
    <RadioGroup
        android:id="@+id/radio_group"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content">
        <RadioButton
            android:id="@+id/rb_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="西瓜"/>
        <RadioButton
            android:id="@+id/rb_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="草莓"/>
        <RadioButton
            android:id="@+id/rb_3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="香蕉"/>
    </RadioGroup>

</LinearLayout>

2.创建一个自己的AlertDialog类,实例化一个AlertDialog对象

在这里插入图片描述
Activity文件           alertDialog_2

package com.example.myapplication;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class alertDialog_2 extends AppCompatActivity {
    private Button btn_my;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alert_dialog_2);
        btn_my=(Button)findViewById(R.id.btn_my);
        btn_my.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                my_aertDialog myDialog=new my_aertDialog(alertDialog_2.this);//用自己的AlertDialog实例化一个AlertDialog对象
                myDialog.show();//显示
            }
        });
    }
}

自己创建的AlertDialog类             my_aertDialog.java

package com.example.myapplication;

import android.app.AlertDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;

public class my_aertDialog extends AlertDialog implements View.OnClickListener {
    Context context;
    CheckBox checkBox1;
    protected my_aertDialog(Context context) {
        super(context);
        this.context=context;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_alert_dialog_xml);
        Button btn_submit=(Button)findViewById(R.id.btn_submit);
        Button btn_cancel=(Button)findViewById(R.id.btn_cancel);
        checkBox1=(CheckBox)findViewById(R.id.ch_1);
        btn_submit.setOnClickListener(this);
        btn_cancel.setOnClickListener(this);
        checkBox1.setChecked(true);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btn_submit:
                showbtn_s();
                break;
            case R.id.btn_cancel:
                showbtn_c();
                break;
        }
    }

    private void showbtn_s() {
        CheckBox checkBox2=(CheckBox)findViewById(R.id.ch_2);
        CheckBox checkBox3=(CheckBox)findViewById(R.id.ch_3);
        String str="";
        if(checkBox1.isChecked())
            str+=checkBox1.getText().toString();
        if(checkBox2.isChecked())
            str+=checkBox2.getText().toString();
        if(checkBox3.isChecked())
            str+=checkBox3.getText().toString();
        Toast.makeText(context,str,Toast.LENGTH_LONG).show();
        my_aertDialog.this.dismiss();
    }
    private void showbtn_c() {
        Toast.makeText(context,"您什么也没有选择.",Toast.LENGTH_LONG).show();
    }
}

alertDialog_2的布局文件            activity_alert_dialog_2.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".alertDialog_2">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <Button
            android:id="@+id/btn_my"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="30dp"
            android:textSize="22dp"
            android:textColor="#aaf"
            android:text="自定义AlertDialog"/>
    </LinearLayout>

</android.support.constraint.ConstraintLayout>

自己创建的AlertDialog类的布局文件(对话框的内容)            my_alert_dialog_xml.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">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="22dp"
            android:text="请选择你喜欢的运动:"/>
        <CheckBox
            android:id="@+id/ch_1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="跑步"/>
        <CheckBox
            android:id="@+id/ch_2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="爬山"/>
        <CheckBox
            android:id="@+id/ch_3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="游泳"/>
        <Button
            android:id="@+id/btn_submit"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:textColor="#aaf"
            android:text="提交"/>
        <Button
            android:id="@+id/btn_cancel"
            android:layout_width="150dp"
            android:layout_height="wrap_content"
            android:textColor="#aaf"
            android:text="取消"/>
    </LinearLayout>
</LinearLayout>

3.小结

相比之下,自己创建的AlertDialog似乎更加的灵活一些.布局什么的更见的精确.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值