如何在安卓上显示一个警告对话框?

1215

我想显示一个包含消息的对话框/弹出窗口,向用户展示“您确定要删除此条目吗?”并添加一个按钮,上面写着“删除”。当点击“删除”按钮时,它应该删除该条目,否则不会执行任何操作。

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


5
这是链接:https://developer.android.com/guide/topics/ui/dialogs.html。该页面介绍了在Android应用程序中创建和管理对话框的方法,包括警告对话框、进度对话框和自定义对话框等。 - Michaël Polla
为什么不使用Material Dialog库呢? - Vivek_Neel
2
有关一个、两个和三个按钮警报的示例,请参见此答案。 - Suragch
可能是重复的问题,参考:如何实现一个确认(是/否)DialogPreference? - Alwin Kesler
38个回答

1973

您可以使用 AlertDialog 来实现此功能,并使用其 Builder 类构建一个对话框。下面的示例使用只需要传入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();

41
"AlertDialog.Builder(this)" 应该被替换为 "AlertDialog.Builder(className.this)" 吗? - Apurva
33
不一定需要。只有在从某些监听器构建警报对话框时才需要。 - Alpha
7
请记住,AlertDialog.Builder无法通过dismiss()方法解除。您可以使用替代方案AlertDialog dialog = new AlertDialog.Builder(context).create();然后您可以正常调用dismiss()来关闭它。 - Fustigador
3
没能解决抽屉菜单选项的问题,但这个可以:https://dev59.com/IV8e5IYBdhLWcg3wF3SV#26097588。 - Amr Hossam
6
不是真的。@Fustigador - Ajay
显示剩余7条评论

395

尝试这段代码:

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();

4
这样做的方式要好得多。@Mahesh创建了一个会话实例,因此可以访问cancel()等功能。 - Subby
2
调用 builder1.show() 直接显示结果没有问题,但是 builder1.create() 是否必要呢? - razz
2
@razzak 是的,这是必要的,因为它提供了对话实例。我们可以使用对话实例来访问特定于对话的方法。 - Mahesh
1
我正在尝试这种方法,但警告窗口弹出并立即消失,没有给我时间阅读它。显然,我也没有时间点击按钮来解除它。有什么想法为什么会这样? - lweingart
1
没事了,我找到原因了。我正在触发一个新的Intent,但它没有等待我的警报窗口弹出,就像我在这里找到的一样:https://dev59.com/5ljUa4cB1Zd3GeqPPDTH - lweingart
显示剩余4条评论

110

David Hedlund发布的代码给我带来了以下错误:

无法添加窗口 - 令牌为空无效

如果你也遇到了同样的错误,请使用以下代码。它是可行的!

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();
        }
    }
});

4
我们不需要同时使用create()show(),因为show()已经创建了描述内容的对话框。根据文档,create()会使用提供给构建器的参数创建一个AlertDialog,但是它不会Dialog.show()该对话框。这允许用户在显示对话框之前执行任何额外的处理。如果您没有其他处理,并且想要创建并显示对话框,请使用show()。 因此,只有当您计划稍后显示对话框并预先加载其内容时,才有用使用create() - Ruchir Baronia
1
将参数从 getApplicationContext() 更改为 MyActivity.this 后,代码开始工作。 - O-9

96

使用 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();
你将会得到以下输出。 android alert dialog 请使用下面的链接查看警告对话框教程。 Android 警告对话框教程

如果XML是我们自己创建的呢? - gumuruh

77

一个简单的示例! 在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();
}

现在创建布局XML文件dialog_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>

现在你可以随时调用openDialog()了 :) 这是上述代码的截图。

Enter image description here

请注意,文本和颜色都来自strings.xmlcolors.xml。您可以定义自己的。


4
Dialog类是对话框的基类,但是应该避免直接实例化Dialog。相反,应该使用以下任一子类:AlertDialog、DatePickerDialog或TimePickerDialog(来自http://developer.android.com/guide/topics/ui/dialogs.html)。 - sweisgerber.dev
这里的“取消”和“同意”不可点击。 - c1ph4
你需要自己定义一个 onClick 监听器,然后在那里面编写代码... - gumuruh

56

1
此外,我在尝试使用自定义内容视图填充系统AlertDialog时,遇到了许多问题,其中之一是如何消除奇怪的背景。 - goRGon

45

你可以使用这段代码:

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();

1
dialog.cancel() 不应该在第二个监听器中调用。 - demaksee
这个教程的链接已经失效了。它会带你到"http://store.hp.com/?jumpid=ps_gymaw6xezr&aoid=98487&003=51875441"。 - JamesDeHart

42

对我而言

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();

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

34
// 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();
}

1
你的代码有误,你需要将 setPositiveButton("cancel" 改为 setNegativeButton("cancel")。 - Benoist Laforge
谢谢,这是一个错误...实际上我想检查一下是否有人可以深入检查发布的代码。而你就是那个人...再次感谢。 - Anil Singhania

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接