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

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

2

从列表中删除一个条目的代码

 /*--dialog for delete entry--*/
private void cancelBookingAlert() {
    AlertDialog dialog;
    final AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this, R.style.AlertDialogCustom);
    alertDialog.setTitle("Delete Entry");
    alertDialog.setMessage("Are you sure you want to delete this entry?");
    alertDialog.setCancelable(false);

    alertDialog.setPositiveButton("Delete", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
           //code to delete entry
        }
    });

    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });

    dialog = alertDialog.create();
    dialog.show();
}

在删除按钮单击事件中调用上面的方法。

2

Kotlin自定义对话框: 如果您想创建自定义对话框

Dialog(activity!!, R.style.LoadingIndicatorDialogStyle)
        .apply {
            // requestWindowFeature(Window.FEATURE_NO_TITLE)
            setCancelable(true)
            setContentView(R.layout.define_your_custom_view_id_here)

            //access your custom view buttons/editText like below.z
            val createBt = findViewById<TextView>(R.id.clipboard_create_project)
            val cancelBt = findViewById<TextView>(R.id.clipboard_cancel_project)
            val clipboard_et = findViewById<TextView>(R.id.clipboard_et)
            val manualOption =
                findViewById<TextView>(R.id.clipboard_manual_add_project_option)

            //if you want to perform any operation on the button do like this

            createBt.setOnClickListener {
                //handle your button click here
                val enteredData = clipboard_et.text.toString()
                if (enteredData.isEmpty()) {
                    Utils.toast("Enter project details")
                } else {
                    navigateToAddProject(enteredData, true)
                    dismiss()
                }
            }

            cancelBt.setOnClickListener {
                dismiss()
            }
            manualOption.setOnClickListener {
                navigateToAddProject("", false)
                dismiss()
            }
            show()
        }

在style.xml中创建LoadingIndicatorDialogStyle。
<style name="LoadingIndicatorDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:statusBarColor">@color/black_transperant</item>
<item name="android:layout_gravity">center</item>
<item name="android:background">@android:color/transparent</item>
<!--<item name="android:windowAnimationStyle">@style/MaterialDialogSheetAnimation</item>-->

2
AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle("This is Title");
    builder.setMessage("This is message for Alert Dialog");
    builder.setPositiveButton("Positive Button", (dialog, which) -> onBackPressed());
    builder.setNegativeButton("Negative Button", (dialog, which) -> dialog.cancel());
    builder.show();

这是一种类似于使用几行代码创建警告对话框的方法。


1
现在,随着Jetpack Compose在安卓中的推出,您可以使用以下代码简单地创建警告对话框。
if (viewModel.shouldDialogOpen.value) {

        AlertDialog(onDismissRequest = { viewModel.shouldDialogOpen.value = false },
            title = { Text("Delete Entry?") },
            text = {
                Text("Are you sure you want to delete this entry?")
            },
            dismissButton = {
                Button(modifier = Modifier.fillMaxWidth(), onClick = {
                    viewModel.shouldDialogOpen.value = false
                }) {
                    Text(text = "Cancel")
                }
            }, confirmButton = {
                Button(modifier = Modifier.fillMaxWidth(), onClick = {
                    viewModel.shouldDialogOpen.value = false
                    viewModel.beginDelete(recipe)
                }) {
                    Text(text = "Okay")
                }
            })
    }

viewModel.shouldDialogOpen中,shouldDialogOpen是viewmodel内的可变状态字段,当我们需要显示或关闭对话框时,会更改其值。

有关Jetpack Compose的更多代码示例:- https://androidlearnersite.wordpress.com/2021/08/03/jetpack-compose-1-0-0-sample-codes/


1

使用Anko(Kotlin开发者的官方库),您可以简单地使用

alert("Alert title").show()

或者更复杂的一个:
alert("Hi, I'm Roy", "Have you tried turning it off and on again?") {
    yesButton { toast("Oh…") }
    noButton {}
}.show()

导入 Anko:

implementation "org.jetbrains.anko:anko:0.10.8"

1
    LayoutInflater inflater = LayoutInflater.from(HistoryActivity.this);
    final View vv = inflater.inflate(R.layout.dialog_processing_tts, null);
    final AlertDialog.Builder alert = new AlertDialog.Builder(
            HistoryActivity.this);
    alert.setTitle("Delete");
    alert.setView(vv);
    alert.setCancelable(false)
            .setPositiveButton("Delete", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    databaseHelperClass.deleteHistory(list.get(position).getID());
                    list.clear();
                    setAdapterForList();

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

    final AlertDialog dialog = alert.create();
    dialog.show();

0
在过去的几天里,我的同事一直在询问我如何在Xamarin.Android中使用AlertDialog,并且几乎所有人都将这个问题作为参考文献发送给我(并没有找到答案),所以这里是Xamarin.Android(C#)版本:
var alertDialog = new AlertDialog.Builder(this) // this: Activity
    .SetTitle("Hello!")
    .SetMessage("Are you sure?")
    .SetPositiveButton("Ok", (sender, e) => { /* ok things */ })
    .SetNegativeButton("Cancel", (sender, e) => { /* cancel things */ })
    .Create();

alertDialog.Show();

// you can customize your AlertDialog, like so
var tvMessage = alertDialog.FindViewById<TextView>(Android.Resource.Id.Message);
tvMessage.TextSize = 13;
// ...

0

您可以创建一个Activity并继承AppCompatActivity。然后在清单文件中添加下一个样式:

<activity android:name=".YourCustomDialog"
            android:theme="Theme.AppCompat.Light.Dialog">
</activity>

通过按钮和文本视图膨胀它

然后像对话框一样使用它。

例如,在LinearLayout中我填充了下一个参数:

android:layout_width="300dp"
android:layout_height="wrap_content"

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