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

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个回答

8

当你想关闭对话框时,请小心使用dialog.dismiss()。在我第一次尝试中,我使用了dismissDialog(0)(可能是从某个地方复制的),但这种方法有时有效。使用系统提供的对象似乎更安全。


7

我想通过分享一个比David Hedlund提供的方法更为动态的方法来补充他的优秀答案,这种方法可以在你需要执行负面操作时以及不需要执行时使用,希望能够帮到你。

private void showAlertDialog(@NonNull Context context, @NonNull String alertDialogTitle, @NonNull String alertDialogMessage, @NonNull String positiveButtonText, @Nullable String negativeButtonText, @NonNull final int positiveAction, @Nullable final Integer negativeAction, @NonNull boolean hasNegativeAction)
{
    AlertDialog.Builder builder;
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder = new AlertDialog.Builder(context, android.R.style.Theme_Material_Dialog_Alert);
    } else {
        builder = new AlertDialog.Builder(context);
    }
    builder.setTitle(alertDialogTitle)
            .setMessage(alertDialogMessage)
            .setPositiveButton(positiveButtonText, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    switch (positiveAction)
                    {
                        case 1:
                            //TODO:Do your positive action here 
                            break;
                    }
                }
            });
            if(hasNegativeAction || negativeAction!=null || negativeButtonText!=null)
            {
            builder.setNegativeButton(negativeButtonText, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    switch (negativeAction)
                    {
                        case 1:
                            //TODO:Do your negative action here
                            break;
                        //TODO: add cases when needed
                    }
                }
            });
            }
            builder.setIcon(android.R.drawable.ic_dialog_alert);
            builder.show();
}

7

Kotlin开发者最简单的解决方案

val alertDialogBuilder: AlertDialog.Builder = AlertDialog.Builder(requireContext())
    alertDialogBuilder.setMessage(msg)
    alertDialogBuilder.setCancelable(true)

    alertDialogBuilder.setPositiveButton(
        getString(android.R.string.ok)
    ) { dialog, _ ->
        dialog.cancel()
    }

    val alertDialog: AlertDialog = alertDialogBuilder.create()
    alertDialog.show()

7
     new AlertDialog.Builder(loginregister.this)
            .setTitle("messege")
            .setPositiveButton("ok", null)
            .setMessage( "user name : " + username + "/n" +
                            "password :" + password + "/n"  )
    .show();

5
public void showSimpleDialog(View view) {
    // Use the Builder class for convenient dialog construction
    AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
    builder.setCancelable(false);
    builder.setTitle("AlertDialog Title");
    builder.setMessage("Simple Dialog Message");
    builder.setPositiveButton("OK!!!", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int id) {
            //
        }
    })
    .setNegativeButton("Cancel ", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {

        }
    });

    // Create the AlertDialog object and return it
    builder.create().show();
}

同时还请查看我关于Android对话框的博客,你将在这里找到所有细节:http://www.fahmapps.com/2016/09/26/dialogs-in-android-part1/


5

这是用kotlin完成的

val builder: AlertDialog.Builder = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            AlertDialog.Builder(this, android.R.style.Theme_Material_Dialog_Alert)
        } else {
            AlertDialog.Builder(this)
        }
        builder.setTitle("Delete Alert!")
                .setMessage("Are you want to delete this entry?")
                .setPositiveButton("YES") { dialog, which ->

                }
                .setNegativeButton("NO") { dialog, which ->

                }
                .setIcon(R.drawable.ic_launcher_foreground)
                .show()

4

您也可以尝试这种方式,它将为您提供材料风格的对话框。

private void showDialog()
{
    String text2 = "<font color=#212121>Medi Notification</font>";//for custom title color

    AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle);
    builder.setTitle(Html.fromHtml(text2));

    String text3 = "<font color=#A4A4A4>You can complete your profile now or start using the app and come back later</font>";//for custom message
    builder.setMessage(Html.fromHtml(text3));

    builder.setPositiveButton("DELETE", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            toast = Toast.makeText(getApplicationContext(), "DELETE", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();              
        }
    });

    builder.setNegativeButton("CANCEL", new DialogInterface.OnClickListener()
    {
        @Override
        public void onClick(DialogInterface dialog, int which)
        {
            toast = Toast.makeText(getApplicationContext(), "CANCEL", Toast.LENGTH_SHORT);
            toast.setGravity(Gravity.CENTER, 0, 0);
            toast.show();
        }
    });
    builder.show();
}

4

尝试一下Kotlin

AlertDialog.Builder(this)
            .setTitle("Title")
            .setPositiveButton("Yes"){ dialog, which ->

            }
            .setNegativeButton("No", null)
            .setMessage("Your given alert message...")
            .show()

4

带有编辑文本的警报对话框

AlertDialog.Builder builder = new AlertDialog.Builder(context);//Context is activity context
final EditText input = new EditText(context);
builder.setTitle(getString(R.string.remove_item_dialog_title));
        builder.setMessage(getString(R.string.dialog_message_remove_item));
 builder.setTitle(getString(R.string.update_qty));
            builder.setMessage("");
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.MATCH_PARENT,
                    LinearLayout.LayoutParams.MATCH_PARENT);
            input.setLayoutParams(lp);
            input.setHint(getString(R.string.enter_qty));
            input.setTextColor(ContextCompat.getColor(context, R.color.textColor));
            input.setInputType(InputType.TYPE_CLASS_NUMBER);
            input.setText("String in edit text you want");
            builder.setView(input);
   builder.setPositiveButton(getString(android.R.string.ok),
                (dialog, which) -> {

//Positive button click event
  });

 builder.setNegativeButton(getString(android.R.string.cancel),
                (dialog, which) -> {
//Negative button click event
                });
        AlertDialog dialog = builder.create();
        dialog.show();

4

创建这个静态方法,并在需要的地方使用它。

public static void showAlertDialog(Context context, String title, String message, String posBtnMsg, String negBtnMsg) {
            AlertDialog.Builder builder = new AlertDialog.Builder(context);
            builder.setTitle(title);
            builder.setMessage(message);
            builder.setPositiveButton(posBtnMsg, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            builder.setNegativeButton(negBtnMsg, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            AlertDialog dialog = builder.create();
            dialog.show();

        }

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