如何在 Android 上显示警报对话框?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2115758/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 04:35:40  来源:igfitidea点击:

How do I display an alert dialog on Android?

androidandroid-dialog

提问by UMAR

I want to display a dialog/popup window with a message to the user that shows "Are you sure you want to delete this entry?" with one button that says 'Delete'. When Deleteis touched, it should delete that entry, otherwise nothing.

我想显示一个对话框/弹出窗口,向用户显示一条消息,显示“您确定要删除此条目吗?” 一个按钮,上面写着“删除”。当Delete被触摸时,它应该删除该条目,否则什么都没有。

I have written a click listener for those buttons, but how do I invoke a dialog or popup and its functionality?

我已经为这些按钮编写了一个单击侦听器,但是如何调用对话框或弹出窗口及其功能?

回答by dxh

You could use an AlertDialogfor this and construct one using its Builderclass. The example below uses the default constructor that only takes in a Contextsince the dialog will inherit the proper theme from the Context you pass in, but there's also a constructor that allows you to specify a specific theme resource as the second parameter if you desire to do so.

您可以AlertDialog为此使用 an并使用其Builder类构造一个。下面的示例使用默认构造函数,该构造函数只接受 a,Context因为对话框将从您传入的 Context 继承正确的主题,但还有一个构造函数允许您将特定的主题资源指定为第二个参数(如果您愿意的话)所以。

new AlertDialog.Builder(context)
    .setTitle("Delete entry")
    .setMessage("Are you sure you want to delete this entry?")

    // Specifying a listener allows you to take an action before dismissing the dialog.
    // The dialog is automatically dismissed when a dialog button is clicked.
    .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) { 
            // Continue with delete operation
        }
     })

    // A null listener allows the button to dismiss the dialog and take no further action.
    .setNegativeButton(android.R.string.no, null)
    .setIcon(android.R.drawable.ic_dialog_alert)
    .show();

回答by Mahesh

Try this code:

试试这个代码:

AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("Write your message here.");
builder1.setCancelable(true);

builder1.setPositiveButton(
    "Yes",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
        }
    });

builder1.setNegativeButton(
    "No",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
        }
    });

AlertDialog alert11 = builder1.create();
alert11.show();

回答by sanath_p

The code which David Hedlund has posted gave me the error:

David Hedlund 发布的代码给了我错误:

Unable to add window — token null is not valid

无法添加窗口 — 令牌空无效

If you are getting the same error use the below code. It works!!

如果您遇到相同的错误,请使用以下代码。有用!!

runOnUiThread(new Runnable() {
    @Override
    public void run() {

        if (!isFinishing()){
            new AlertDialog.Builder(YourActivity.this)
              .setTitle("Your Alert")
              .setMessage("Your Message")
              .setCancelable(false)
              .setPositiveButton("ok", new OnClickListener() {
                  @Override
                  public void onClick(DialogInterface dialog, int which) {
                      // Whatever...
                  }
              }).show();
        }
    }
});

回答by Madan Sapkota

Just a simple one! Create a dialog method, something like this anywhere in your Java class:

只是一个简单的!在 Java 类中的任何位置创建一个对话框方法,如下所示:

public void openDialog() {
    final Dialog dialog = new Dialog(context); // Context, this, etc.
    dialog.setContentView(R.layout.dialog_demo);
    dialog.setTitle(R.string.dialog_title);
    dialog.show();
}

Now create Layout XML dialog_demo.xmland create your UI/design. Here is a sample one I created for demo purposes:

现在创建布局 XMLdialog_demo.xml并创建您的 UI/设计。这是我为演示目的创建的示例:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <TextView
        android:id="@+id/dialog_info"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="10dp"
        android:text="@string/dialog_text"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_below="@id/dialog_info">

        <Button
            android:id="@+id/dialog_cancel"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.50"
            android:background="@color/dialog_cancel_bgcolor"
            android:text="Cancel"/>

        <Button
            android:id="@+id/dialog_ok"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="0.50"
            android:background="@color/dialog_ok_bgcolor"
            android:text="Agree"/>
    </LinearLayout>
</RelativeLayout>

Now you can call openDialog()from anywhere you like :) Here is the screenshot of above code.

现在你可以openDialog()从你喜欢的任何地方调用:) 这是上面代码的屏幕截图。

Enter image description here

在此处输入图片说明

Note that text and color are used from strings.xmland colors.xml. You can define your own.

请注意,文本和颜色是从strings.xml和 使用的colors.xml。你可以定义你自己的。

回答by Richard Kamere

Use AlertDialog.Builder:

使用AlertDialog.Builder

AlertDialog alertDialog = new AlertDialog.Builder(this)
//set icon 
 .setIcon(android.R.drawable.ic_dialog_alert)
//set title
.setTitle("Are you sure to Exit")
//set message
.setMessage("Exiting will call finish() method")
//set positive button
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
   //set what would happen when positive button is clicked    
        finish();
    }
})
//set negative button
.setNegativeButton("No", new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialogInterface, int i) {
   //set what should happen when negative button is clicked
        Toast.makeText(getApplicationContext(),"Nothing Happened",Toast.LENGTH_LONG).show();
    }
})
.show();

You will get the following output.

您将获得以下输出。

android alert dialog

安卓警报对话框

To view alert dialog tutorial use the link below.

要查看警报对话框教程,请使用下面的链接。

Android Alert Dialog Tutorial

Android 警报对话框教程

回答by goRGon

Nowadays it's better to use DialogFragment instead of direct AlertDialog creation.

现在最好使用 DialogFragment 而不是直接创建 AlertDialog。

回答by romain guy

You can use this code:

您可以使用此代码:

AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(
    AlertDialogActivity.this);

// Setting Dialog Title
alertDialog2.setTitle("Confirm Delete...");

// Setting Dialog Message
alertDialog2.setMessage("Are you sure you want delete this file?");

// Setting Icon to Dialog
alertDialog2.setIcon(R.drawable.delete);

// Setting Positive "Yes" Btn
alertDialog2.setPositiveButton("YES",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // Write your code here to execute after dialog
            Toast.makeText(getApplicationContext(),
                           "You clicked on YES", Toast.LENGTH_SHORT)
                    .show();
        }
    });

// Setting Negative "NO" Btn
alertDialog2.setNegativeButton("NO",
    new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            // Write your code here to execute after dialog
            Toast.makeText(getApplicationContext(),
                           "You clicked on NO", Toast.LENGTH_SHORT)
                    .show();
            dialog.cancel();
        }
    });

// Showing Alert Dialog
alertDialog2.show();

回答by Hoàng ??ng

for me

为了我

new AlertDialog.Builder(this)
    .setTitle("Closing application")
    .setMessage("Are you sure you want to exit?")
    .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
          @Override
          public void onClick(DialogInterface dialog, int which) {

          }
     }).setNegativeButton("No", null).show();

回答by Anil Singhania

// Dialog box

public void dialogBox() {
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
    alertDialogBuilder.setMessage("Click on Image for tag");
    alertDialogBuilder.setPositiveButton("Ok",
        new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
        }
    });

    alertDialogBuilder.setNegativeButton("cancel",
        new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface arg0, int arg1) {

        }
    });

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

回答by user3219477

new AlertDialog.Builder(context)
    .setTitle("title")
    .setMessage("message")
    .setPositiveButton(android.R.string.ok, null)
    .show();