Android 简明教程

Android - Alert Dialog

有时在你的应用程序中,如果你想针对用户执行的任何特定操作询问用户在是或否之间做出决定,则无需改变屏幕,便可使用警报对话框,同时仍保留在当前活动中。

Some times in your application, if you wanted to ask the user about taking a decision between yes or no in response of any particular action taken by the user, by remaining in the same activity and without changing the screen, you can use Alert Dialog.

要创建警报对话框,你需要创建一个 AlertDialogBuilder 对象,它是 AlertDialog 的一个内部类。其语法如下:

In order to make an alert dialog, you need to make an object of AlertDialogBuilder which an inner class of AlertDialog. Its syntax is given below

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

现在你必须使用 AlertDialogBuilder 类的对象设置肯定(是)按钮或否定(否)按钮。其语法是:

Now you have to set the positive (yes) or negative (no) button using the object of the AlertDialogBuilder class. Its syntax is

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

除此之外,你可以使用生成器类提供其他功能来自定义警报对话框。这些功能如下:

Apart from this , you can use other functions provided by the builder class to customize the alert dialog. These are listed below

Sr.No

Method type & description

1

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

2

setCancelable(boolean cancel able) This method sets the property that the dialog can be cancelled or not

3

setMessage(CharSequence message) This method sets the message to be displayed in the alert dialog

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

5

setOnCancelListener(DialogInterface.OnCancelListener onCancelListener) This method Sets the callback that will be called if the dialog is cancelled.

6

setTitle(CharSequence title) This method set the title to be appear in the dialog

在创建并设置对话框生成器之后,你可以通过调用生成器类的 create() 方法创建警报对话框。其语法是:

After creating and setting the dialog builder , you will create an alert dialog by calling the create() method of the builder class. Its syntax is

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

这会创建警报对话框并将其显示在屏幕上。

This will create the alert dialog and will show it on the screen.

Dialog fragment

在进入示例之前,我们应该了解对话框片段。对话框片段是一种可以将片段显示在对话框中的片段

Before enter into an example we should need to know dialog fragment.Dialog fragment is a fragment which can show fragment in dialog box

public class DialogFragment extends DialogFragment {
   @Override
   public Dialog onCreateDialog(Bundle savedInstanceState) {
      // Use the Builder class for convenient dialog construction
      AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
      builder.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int id) {
            toast.makeText(this,"enter a text here",Toast.LENTH_SHORT).show();
         }
      })
      .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int id) {
            finish();
         });
         // Create the AlertDialog object and return it
         return builder.create();
      }
   }
}

List dialog

它用于在对话框中显示项目列表。比如,用户需要从项目列表中选择一项或需要从多个项目列表中点击某个项目。在此情况下,我们可以使用列表对话框。

It has used to show list of items in a dialog box.For suppose, user need to select a list of items or else need to click a item from multiple list of items.At this situation we can use list dialog.

public Dialog onCreateDialog(Bundle savedInstanceState) {
   AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
   builder.setTitle(Pick a Color)

   .setItems(R.array.colors_array, new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which) {
         // The 'which' argument contains the index position
         // of the selected item
      }
   });
   return builder.create();
}

Single-choice list dialog

它用于将单选列表添加到对话框中。我们可根据用户选择进行勾选或取消勾选。

It has used to add single choice list to Dialog box.We can check or uncheck as per user choice.

public Dialog onCreateDialog(Bundle savedInstanceState) {
   mSelectedItems = new ArrayList();
   AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());

   builder.setTitle("This is list choice dialog box");
   .setMultiChoiceItems(R.array.toppings, null,
      new DialogInterface.OnMultiChoiceClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int which, boolean isChecked) {

         if (isChecked) {
            // If the user checked the item, add it to the selected items
            mSelectedItems.add(which);
         }

         else if (mSelectedItems.contains(which)) {
            // Else, if the item is already in the array, remove it
            mSelectedItems.remove(Integer.valueOf(which));
         }
      }
   })

   // Set the action buttons
   .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int id) {
         // User clicked OK, so save the mSelectedItems results somewhere
         // or return them to the component that opened the dialog
         ...
      }
   })

   .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
      @Override
      public void onClick(DialogInterface dialog, int id) {
         ...
      }
   });
   return builder.create();
}

Example

以下示例演示了如何在 Android 中使用 AlertDialog。

The following example demonstrates the use of AlertDialog in android.

为了试验此示例,您需要在模拟器或实际设备上运行此示例。

To experiment with this example , you need to run this on an emulator or an actual device.

Steps

Description

1

You will use Android studio to create an Android application and name it as My Application under a package com.example.sairamkrishna.myapplication.

2

Modify src/MainActivity.java file to add alert dialog code to launch the dialog.

3

Modify layout XML file res/layout/activity_main.xml add any GUI component if required.

4

No need to change default string constants. Android studio takes care of default strings at values/string.xml

5

Run the application and choose a running android device and install the application on it and verify the results.

以下是修改后的代码 src/MainActivity.java

Here is the modified code of src/MainActivity.java

package com.example.sairamkrishna.myapplication;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
   }

   public void open(View view){
      AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
      alertDialogBuilder.setMessage("Are you sure,
         You wanted to make decision");
      alertDialogBuilder.setPositiveButton("yes",
         new DialogInterface.OnClickListener() {
         @Override
         public void onClick(DialogInterface arg0, int arg1) {
            Toast.makeText(MainActivity.this,"You clicked yes
               button",Toast.LENGTH_LONG).show();
         }
      });

      alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
         Override
         public void onClick(DialogInterface dialog, int which) {
            finish();
         }
      });

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

以下是修改后的代码 res/layout/activity_main.xml

Here is the modified code of res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
   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:paddingLeft="@dimen/activity_horizontal_margin"
   android:paddingRight="@dimen/activity_horizontal_margin"
   android:paddingTop="@dimen/activity_vertical_margin"
   android:paddingBottom="@dimen/activity_vertical_margin"
   tools:context=".MainActivity">

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Alert Dialog"
      android:id="@+id/textView"
      android:textSize="35dp"
      android:layout_alignParentTop="true"
      android:layout_centerHorizontal="true" />

   <TextView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Tutorialspoint"
      android:id="@+id/textView2"
      android:textColor="#ff3eff0f"
      android:textSize="35dp"
      android:layout_below="@+id/textView"
      android:layout_centerHorizontal="true" />

   <ImageView
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:id="@+id/imageView"
      android:src="@drawable/abc"
      android:layout_below="@+id/textView2"
      android:layout_alignRight="@+id/textView2"
      android:layout_alignEnd="@+id/textView2"
      android:layout_alignLeft="@+id/textView"
      android:layout_alignStart="@+id/textView" />
   <Button
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:text="Alert dialog"
      android:id="@+id/button"
      android:layout_below="@+id/imageView"
      android:layout_alignRight="@+id/textView2"
      android:layout_alignEnd="@+id/textView2"
      android:layout_marginTop="42dp"
      android:onClick="open"
      android:layout_alignLeft="@+id/imageView"
      android:layout_alignStart="@+id/imageView" />

</RelativeLayout>

以下是 Strings.xml

Here is of*Strings.xml*

<resources>
    <string name="app_name">My Application</string>
</resources>

以下是 AndroidManifest.xml 的默认代码

Here is the default code of AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
   package="com.example.sairamkrishna.myapplication" >

   <application
      android:allowBackup="true"
      android:icon="@drawable/ic_launcher"
      android:label="@string/app_name"
      android:theme="@style/AppTheme" >

      <activity
         android:name="com.example.sairamkrishna.myapplication.MainActivity"
         android:label="@string/app_name" >

         <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>

      </activity>

   </application>
</manifest>

让我们尝试运行您的应用程序。我认为您已将您的实际 Android 移动设备与您的计算机连接起来。若要从 Android Studio 运行该应用程序,请打开您项目中的某个活动文件并单击工具栏中的运行图标。在启动应用程序之前,]Android Studio 将显示以下窗口,以选择您希望在其中运行您的 Android 应用程序的选项。

Let’s try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from Android studio, open one of your project’s activity files and click Run icon from the toolbar. Before starting your application, ]Android studio will display following window to select an option where you want to run your Android application.

alert dialog

选择您的选项,然后单击它。例如,如果您单击了“是”按钮,结果将如下

Select your an option and then click on it. For suppose, if you have clicked on yes button, then result would as follows

alert dialog result

如果您单击了“否”按钮,它将调用 finish() 并且关闭您的应用程序。

if you click on no button it will call finish() and it will close your application.