Android AlertDialog

Android AlertDialog is used in cases when we require the user to choose an option from the prompt presented on the screen. In this tutorial we will be discussing about creating different Alert Dialog with one button (OK button), two buttons (Yes and No) and three buttons (Yes, No and Cancel).

如果我们要求用户从屏幕上显示的提示中选择一个选项,则可以使用Android AlertDialog。 在本教程中,我们将讨论如何使用一个按钮(确定按钮),两个按钮(是和否)和三个按钮(是,否和取消)来创建不同的警报对话框。

Android AlertDialog (Android AlertDialog)

Below is the final android alert dialog application we will create in this tutorial.

以下是我们将在本教程中创建的最终android警报对话框应用程序。

Android AlertDialog is one of the most important and basic component in Android applications. Alert dialog box is used to show alerts to the users, get confirmation from the users. In order to make an alert dialog, we need to make an object of AlertDialogBuilder which is an inner class of AlertDialog. Its syntax is given below.

Android AlertDialog是Android应用程序中最重要和最基本的组件之一。 警报对话框用于向用户显示警报,并获得用户的确认。 为了使一个警告对话框,我们需要做的一个目的AlertDialogBuilder这是一个内部类的AlertDialog 。 其语法如下。

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

Android AlertDialog组件 (Android AlertDialog Components)

  1. Title: Note that title is optional

    标题 :请注意,标题是可选的
  2. Content: This displays the message to the user. It can be a string message, a list or custom layout

    内容 :向用户显示消息。 它可以是字符串消息,列表或自定义布局
  3. Action Buttons: These buttons are of three types. They are Positive, Negative and Neutral action buttons. An alert dialog can have maximum three action buttons. In general following are the conventions for the buttons:
    • If you want the user to accept the action, use Positive action button. It is normally displayed as OK/YES.
    • If the user wants to cancel the action, then you can use Negative action button (NO).
    • If the user wants to postpone the decision use Neutral action button (Later).

    动作按钮 :这些按钮有三种类型。 它们是正,负和中性操作按钮。 一个警报对话框最多可以包含三个操作按钮。 通常,以下是按钮的约定:
    • 如果希望用户接受该操作,请使用“正面操作”按钮。 通常显示为OK / YES。
    • 如果用户要取消操作,则可以使用“否定操作”按钮(NO)。
    • 如果用户希望推迟决策,请使用“中立行动”按钮(稍后)。

Now we need to set the methods of these buttons using AlertDialogBuilder class. The syntax is given below.

现在,我们需要使用AlertDialogBuilder类设置这些按钮的方法。 语法如下。

alertDialogBuilder.setPositiveButton(CharSequence text, DialogInterface.OnClickListener listener);
alertDialogBuilder.setNegativeButton(CharSequence text, DialogInterface.OnClickListener listener);
alertDialogBuilder.setNeutralButton(CharSequence text, DialogInterface.OnClickListener listener);

The first argument is the text to be displayed. The second argument is the listener to be invoked when the positive button is pressed.

第一个参数是要显示的文本。 第二个参数是按下肯定按钮时要调用的侦听器。

AlertDialog函数 (AlertDialog Functions)

Besides this, there are some functions available to customise the alert dialog as given below.

除此之外,还有一些功能可用于自定义警报对话框,如下所示。

  1. setIcon(Drawable icon): This method set the icon of the alert dialog box

    setIcon(Drawable icon) :此方法设置警报对话框的图标
  2. setCancelable(boolean cancelable): This method sets the property that the dialog can be cancelled or not

    setCancelable(boolean cancelable) :此方法设置对话框是否可以取消的属性
  3. setMessage(CharSequence message): This method sets the message to be displayed in the alert dialog

    setMessage(CharSequence message) :此方法设置要在警报对话框中显示的消息
  4. setMultiChoiceItems(CharSequence[] items, boolean[] checkedItems, DialogInterface.OnMultiChoiceClickListener listener): This method sets list of items to be displayed in the dialog as the content. The selected option will be notified by the listener

    setMultiChoiceItems(CharSequence [] items,boolean [] checkedItems,DialogInterface.OnMultiChoiceClickListener侦听器) :此方法设置要在对话框中显示的项目列表作为内容。 选定的选项将由侦听器通知
  5. setOnCancelListener(DialogInterface.OnCancelListener onCancelListener): This method Sets the callback that will be called if the dialog is cancelled

    setOnCancelListener(DialogInterface.OnCancelListener onCancelListener) :此方法设置在取消对话框时将调用的回调
  6. setTitle(CharSequence title): This method set the title to be appear in the dialog

    setTitle(CharSequence title) :此方法设置标题显示在对话框中
  7. getListView(): This function is used to get the list view used in the dialog

    getListView() :此函数用于获取对话框中使用的列表视图

After creating and setting the dialog builder, we need to create an alert dialog by calling the create() method of the builder class. Its syntax is shown below.

创建并设置对话框构建器后,我们需要通过调用构建器类的create()方法来创建警报对话框。 其语法如下所示。

AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();

Android AlertDialog示例项目结构 (Android AlertDialog Example Project Structure)

This application consists of three buttons which opens alert dialog containing the respective number of buttons.

该应用程序由三个按钮组成,这些按钮可打开包含相应按钮数量的警报对话框。

Android警报对话框项目代码 (Android Alert Dialog Project Code)

The application consists of a single activity. The layout of the activity has three buttons as shown in the xml file below.

该应用程序包含一个活动。 活动的布局具有三个按钮,如下面的xml文件所示。

activity_alert.xml

activity_alert.xml

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".AlertActivity" >

    <Button
        android:id="@+id/one_button_alert"
        android:layout_width="200dip"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_marginTop="25dip"
        android:layout_marginLeft="20dip"
        android:text="Single Button Alert" />
    <Button
        android:id="@+id/two_button_alert"
        android:layout_width="200dip"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/one_button_alert"
        android:layout_marginLeft="20dip"
        android:text="Two Buttons Alert" />
    <Button
        android:id="@+id/three_button_alert"
        android:layout_width="200dip"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_below="@id/two_button_alert"
        android:layout_marginLeft="20dip"
        android:text="Three Buttons Alert" />
</RelativeLayout>

The AlertActivity.java is given below. Each button click invokes an alert dialog with different set of action buttons. On clicking action buttons a Toast corresponding to that action button is displayed.

下面给出AlertActivity.java 。 每次单击按钮都会调用带有不同操作按钮集的警报对话框。 单击动作按钮时,将显示与该动作按钮相对应的Toast。

package com.journaldev.alertdialog;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class AlertActivity extends Activity {
    private Button button1;
    private Button button2;
    private Button button3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_alert);
        button1 = (Button) findViewById(R.id.one_button_alert);
        button2 = (Button) findViewById(R.id.two_button_alert);
        button3 = (Button) findViewById(R.id.three_button_alert);

        button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        AlertActivity.this);
                builder.setTitle("Sample Alert");
                builder.setMessage("One Action Button Alert");
                builder.setPositiveButton("OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                Toast.makeText(getApplicationContext(),"Yes is clicked",Toast.LENGTH_LONG).show();
                            }
                        });
                builder.show();
            }
        });
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        AlertActivity.this);
                builder.setTitle("Sample Alert");
                builder.setMessage("Two Action Buttons Alert Dialog");
                builder.setNegativeButton("NO",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                Toast.makeText(getApplicationContext(),"No is clicked",Toast.LENGTH_LONG).show();
                            }
                        });
                builder.setPositiveButton("YES",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                Toast.makeText(getApplicationContext(),"Yes is clicked",Toast.LENGTH_LONG).show();
                            }
                        });
                builder.show();
            }
        });
        button3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                AlertDialog.Builder builder = new AlertDialog.Builder(
                        AlertActivity.this);
                builder.setTitle("Sample Alert");
                builder.setMessage("Three Action Buttons Alert Dialog");
                builder.setNegativeButton("NO",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                Toast.makeText(getApplicationContext(),"No is clicked",Toast.LENGTH_LONG).show();
                            }
                        });
                builder.setPositiveButton("YES",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                Toast.makeText(getApplicationContext(),"Yes is clicked",Toast.LENGTH_LONG).show();
                            }
                        });
                builder.setNeutralButton("CANCEL",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                Toast.makeText(getApplicationContext(),"Cancel is clicked",Toast.LENGTH_LONG).show();
                            }
                        });

                builder.show();
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

}

This brings an end to this tutorial. We’ll discuss how to customize alert dialog at length later. You can download the final android alert dialog project from the below link.

本教程到此结束。 稍后我们将详细讨论如何自定义警报对话框。 您可以从下面的链接下载最终的android Alert对话框项目。

Reference: Official Doc

参考: 官方文件

翻译自: https://www.journaldev.com/9463/android-alertdialog

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值