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

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

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

1684253 次浏览

您可以为此使用AlertDialog并使用其Builder类构造一个。下面的示例使用仅接收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();

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

试试这个代码:

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

您可以使用此代码:

AlertDialog.Builder alertDialog2 = new AlertDialog.Builder(AlertDialogActivity.this);
// Setting Dialog TitlealertDialog2.setTitle("Confirm Delete...");
// Setting Dialog MessagealertDialog2.setMessage("Are you sure you want delete this file?");
// Setting Icon to DialogalertDialog2.setIcon(R.drawable.delete);
// Setting Positive "Yes" BtnalertDialog2.setPositiveButton("YES",new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {// Write your code here to execute after dialogToast.makeText(getApplicationContext(),"You clicked on YES", Toast.LENGTH_SHORT).show();}});
// Setting Negative "NO" BtnalertDialog2.setNegativeButton("NO",new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int which) {// Write your code here to execute after dialogToast.makeText(getApplicationContext(),"You clicked on NO", Toast.LENGTH_SHORT).show();dialog.cancel();}});
// Showing Alert DialogalertDialog2.show();

这对您绝对有帮助。尝试此代码:单击一个按钮,您可以放置一个、两个或三个带有警报对话框的按钮…

SingleButtton.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {// Creating alert Dialog with one Button
AlertDialog alertDialog = new AlertDialog.Builder(AlertDialogActivity.this).create();
// Setting Dialog TitlealertDialog.setTitle("Alert Dialog");
// Setting Dialog MessagealertDialog.setMessage("Welcome to Android Application");
// Setting Icon to DialogalertDialog.setIcon(R.drawable.tick);
// Setting OK ButtonalertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which){// Write your code here to execute after dialog    closedToast.makeText(getApplicationContext(),"You clicked on OK", Toast.LENGTH_SHORT).show();}});
// Showing Alert MessagealertDialog.show();}});
btnAlertTwoBtns.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {// Creating alert Dialog with two Buttons
AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertDialogActivity.this);
// Setting Dialog TitlealertDialog.setTitle("Confirm Delete...");
// Setting Dialog MessagealertDialog.setMessage("Are you sure you want delete this?");
// Setting Icon to DialogalertDialog.setIcon(R.drawable.delete);
// Setting Positive "Yes" ButtonalertDialog.setPositiveButton("YES",new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog,int which) {// Write your code here to execute after dialogToast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show();}});
// Setting Negative "NO" ButtonalertDialog.setNegativeButton("NO",new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog,    int which) {// Write your code here to execute after dialogToast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT).show();dialog.cancel();}});
// Showing Alert MessagealertDialog.show();}});
btnAlertThreeBtns.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {// Creating alert Dialog with three Buttons
AlertDialog.Builder alertDialog = new AlertDialog.Builder(AlertDialogActivity.this);
// Setting Dialog TitlealertDialog.setTitle("Save File...");
// Setting Dialog MessagealertDialog.setMessage("Do you want to save this file?");
// Setting Icon to DialogalertDialog.setIcon(R.drawable.save);
// Setting Positive Yes ButtonalertDialog.setPositiveButton("YES",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {// User pressed Cancel button. Write Logic HereToast.makeText(getApplicationContext(),"You clicked on YES",Toast.LENGTH_SHORT).show();}});
// Setting Negative No Button... Neutral means in between yes and cancel buttonalertDialog.setNeutralButton("NO",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {// User pressed No button. Write Logic HereToast.makeText(getApplicationContext(),"You clicked on NO", Toast.LENGTH_SHORT).show();}});
// Setting Positive "Cancel" ButtonalertDialog.setNegativeButton("Cancel",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {// User pressed Cancel button. Write Logic HereToast.makeText(getApplicationContext(),"You clicked on Cancel",Toast.LENGTH_SHORT).show();}});// Showing Alert MessagealertDialog.show();}});

我创建了一个对话框来询问一个人是否想打电话给一个人。

import android.app.Activity;import android.app.AlertDialog;import android.content.DialogInterface;import android.content.Intent;import android.net.Uri;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;import android.widget.ImageView;import android.widget.Toast;
public class Firstclass extends Activity {
@Overrideprotected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.first);
ImageView imageViewCall = (ImageView) findViewById(R.id.ring_mig);
imageViewCall.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v){try{showDialog("0728570527");}catch (Exception e){e.printStackTrace();}}});}
public void showDialog(final String phone) throws Exception{AlertDialog.Builder builder = new AlertDialog.Builder(Firstclass.this);
builder.setMessage("Ring: " + phone);
builder.setPositiveButton("Ring", new DialogInterface.OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which){Intent callIntent = new Intent(Intent.ACTION_DIAL);// (Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:" + phone));
startActivity(callIntent);
dialog.dismiss();}});
builder.setNegativeButton("Avbryt", new DialogInterface.OnClickListener(){@Overridepublic void onClick(DialogInterface dialog, int which){dialog.dismiss();}});
builder.show();}}

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

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

无法添加窗口-令牌null无效

如果您收到相同的错误,请使用下面的代码。它有效!!

runOnUiThread(new Runnable() {@Overridepublic void run() {
if (!isFinishing()){new AlertDialog.Builder(YourActivity.this).setTitle("Your Alert").setMessage("Your Message").setCancelable(false).setPositiveButton("ok", new OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {// Whatever...}}).show();}}});
// 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() {
@Overridepublic void onClick(DialogInterface arg0, int arg1) {}});
alertDialogBuilder.setNegativeButton("cancel",new DialogInterface.OnClickListener() {
@Overridepublic void onClick(DialogInterface arg0, int arg1) {
}});
AlertDialog alertDialog = alertDialogBuilder.create();alertDialog.show();}

只是一个简单的方法!创建一个对话框方法,在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();}

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

<?xml version="1.0" encoding="utf-8"?><RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="wrap_content">
<TextViewandroid:id="@+id/dialog_info"android:layout_width="match_parent"android:layout_height="wrap_content"android:padding="10dp"android:text="@string/dialog_text"/>
<LinearLayoutandroid:layout_width="match_parent"android:layout_height="40dp"android:layout_below="@id/dialog_info">
<Buttonandroid: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"/>
<Buttonandroid: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():)这是上面代码的截图。

在此处输入图像描述

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

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

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 messagebuilder.setMessage(Html.fromHtml(text3));
builder.setPositiveButton("DELETE", new DialogInterface.OnClickListener(){@Overridepublic 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(){@Overridepublic void onClick(DialogInterface dialog, int which){toast = Toast.makeText(getApplicationContext(), "CANCEL", Toast.LENGTH_SHORT);toast.setGravity(Gravity.CENTER, 0, 0);toast.show();}});builder.show();}
public void showSimpleDialog(View view) {// Use the Builder class for convenient dialog constructionAlertDialog.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() {@Overridepublic void onClick(DialogInterface dialog, int id) {//}}).setNegativeButton("Cancel ", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {
}});
// Create the AlertDialog object and return itbuilder.create().show();}

也看看我的博客在Android中的对话,你会在这里找到所有的细节:http://www.fahmapps.com/2016/09/26/dialogs-in-android-part1/

这是如何创建警报对话框的基本示例:

AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);dialog.setCancelable(false);dialog.setTitle("Dialog on Android");dialog.setMessage("Are you sure you want to delete this entry?" );dialog.setPositiveButton("Delete", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int id) {//Action for "Delete".}}).setNegativeButton("Cancel ", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {//Action for "Cancel".}});
final AlertDialog alert = dialog.create();alert.show();

在此处输入图片描述

你可以试试这个……

    AlertDialog.Builder dialog = new AlertDialog.Builder(MainActivity.this);dialog.setCancelable(false);dialog.setTitle("Dialog on Android");dialog.setMessage("Are you sure you want to delete this entry?" );dialog.setPositiveButton("Delete", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int id) {//Action for "Delete".}}).setNegativeButton("Cancel ", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {//Action for "Cancel".}});
final AlertDialog alert = dialog.create();alert.show();

更多信息,检查此链接…

对我

new AlertDialog.Builder(this).setTitle("Closing application").setMessage("Are you sure you want to exit?").setPositiveButton("Yes", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {
}}).setNegativeButton("No", null).show();

试试这个代码

AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MainActivity.this);
// set titlealertDialogBuilder.setTitle("AlertDialog Title");
// set dialog messagealertDialogBuilder.setMessage("Some Alert Dialog message.").setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int id) {Toast.makeText(this, "OK button click ", Toast.LENGTH_SHORT).show();
}}).setNegativeButton("CANCEL",new DialogInterface.OnClickListener() {public void onClick(DialogInterface dialog, int id) {Toast.makeText(this, "CANCEL button click ", Toast.LENGTH_SHORT).show();
dialog.cancel();}});
// create alert dialogAlertDialog alertDialog = alertDialogBuilder.create();
// show italertDialog.show();
   new AlertDialog.Builder(v.getContext()).setMessage("msg to display!").show();

您可以使用AlertDialog.Builder创建对话框

试试这个:

AlertDialog.Builder builder = new AlertDialog.Builder(this);builder.setMessage("Are you sure you want to delete this entry?");
builder.setPositiveButton("Yes, please", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {//perform any actionToast.makeText(getApplicationContext(), "Yes clicked", Toast.LENGTH_SHORT).show();}});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {//perform any actionToast.makeText(getApplicationContext(), "No clicked", Toast.LENGTH_SHORT).show();}});
//creating alert dialogAlertDialog alertDialog = builder.create();alertDialog.show();

要更改警报对话框的正负按钮的颜色,您可以在alertDialog.show();之后写入以下两行

alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.colorPrimary));alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.colorPrimaryDark));

在此处输入图片描述

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

使用创建对话框

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() {@Overridepublic void onClick(DialogInterface dialogInterface, int i) {//set what would happen when positive button is clickedfinish();}})//set negative button.setNegativeButton("No", new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialogInterface, int i) {//set what should happen when negative button is clickedToast.makeText(getApplicationContext(),"Nothing Happened",Toast.LENGTH_LONG).show();}}).show();

您将获得以下输出。

Android警报对话框

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

Android警报对话框教程

您可以创建活动并扩展AppCompatActivity。然后在清单中输入下一个样式:

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

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

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

例如,在linearLayout中,我填写下一个参数:

android:layout_width="300dp"android:layout_height="wrap_content"
showDialog(MainActivity.this, "title", "message", "OK", "Cancel", {...}, {...});

静态编程语言

fun showDialog(context: Context, title: String, msg: String,positiveBtnText: String, negativeBtnText: String?,positiveBtnClickListener: DialogInterface.OnClickListener,negativeBtnClickListener: DialogInterface.OnClickListener?): AlertDialog {val builder = AlertDialog.Builder(context).setTitle(title).setMessage(msg).setCancelable(true).setPositiveButton(positiveBtnText, positiveBtnClickListener)if (negativeBtnText != null)builder.setNegativeButton(negativeBtnText, negativeBtnClickListener)val alert = builder.create()alert.show()return alert}

Java

public static AlertDialog showDialog(@NonNull Context context, @NonNull String title, @NonNull String msg,@NonNull String positiveBtnText, @Nullable String negativeBtnText,@NonNull DialogInterface.OnClickListener positiveBtnClickListener,@Nullable DialogInterface.OnClickListener negativeBtnClickListener) {AlertDialog.Builder builder = new AlertDialog.Builder(context).setTitle(title).setMessage(msg).setCancelable(true).setPositiveButton(positiveBtnText, positiveBtnClickListener);if (negativeBtnText != null)builder.setNegativeButton(negativeBtnText, negativeBtnClickListener);AlertDialog alert = builder.create();alert.show();return alert;}

我想通过分享一个比他发布的更动态的方法来补充大卫·赫德伦德的伟大答案,这样当你有一个消极的行动要执行时,它就可以使用,当你没有的时候,我希望它有帮助。

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 herebreak;}}});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 herebreak;//TODO: add cases when needed}}});}builder.setIcon(android.R.drawable.ic_dialog_alert);builder.show();}
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();

这是一种使用一些代码行创建警报对话框的方法。

从列表中删除条目的代码

 /*--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() {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.dismiss();}});
dialog = alertDialog.create();dialog.show();}

单击删除按钮调用上述方法

这是在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()

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

AlertDialog.Builder builder = new AlertDialog.Builder(context);//Context is activity contextfinal 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();

创建这个静态方法并在任何你想要的地方使用它。

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() {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.cancel();}});builder.setNegativeButton(negBtnMsg, new DialogInterface.OnClickListener() {@Overridepublic void onClick(DialogInterface dialog, int which) {dialog.cancel();}});AlertDialog dialog = builder.create();dialog.show();
}

我在按钮onClick中使用了这个AlertDialog方法:

button.setOnClickListener(v -> {AlertDialog.Builder builder = new AlertDialog.Builder(this);LayoutInflater layoutInflaterAndroid = LayoutInflater.from(this);View view = layoutInflaterAndroid.inflate(R.layout.cancel_dialog, null);builder.setView(view);builder.setCancelable(false);final AlertDialog alertDialog = builder.create();alertDialog.show();
view.findViewById(R.id.yesButton).setOnClickListener(v -> onBackPressed());view.findViewById(R.id.nobutton).setOnClickListener(v -> alertDialog.dismiss());});

dialog.xml

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical">
<TextViewandroid:id="@+id/textmain"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="5dp"android:gravity="center"android:padding="5dp"android:text="@string/warning"android:textColor="@android:color/black"android:textSize="18sp"android:textStyle="bold"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toTopOf="parent" />

<TextViewandroid:id="@+id/textpart2"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_margin="5dp"android:gravity="center"android:lines="2"android:maxLines="2"android:padding="5dp"android:singleLine="false"android:text="@string/dialog_cancel"android:textAlignment="center"android:textColor="@android:color/black"android:textSize="15sp"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/textmain" />

<TextViewandroid:id="@+id/yesButton"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginStart="40dp"android:layout_marginTop="5dp"android:layout_marginEnd="40dp"android:layout_marginBottom="5dp"android:background="#87cefa"android:gravity="center"android:padding="10dp"android:text="@string/yes"android:textAlignment="center"android:textColor="@android:color/black"android:textSize="15sp"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/textpart2" />

<TextViewandroid:id="@+id/nobutton"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginStart="40dp"android:layout_marginTop="5dp"android:layout_marginEnd="40dp"android:background="#87cefa"android:gravity="center"android:padding="10dp"android:text="@string/no"android:textAlignment="center"android:textColor="@android:color/black"android:textSize="15sp"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/yesButton" />

<TextViewandroid:layout_width="match_parent"android:layout_height="20dp"android:layout_margin="5dp"android:padding="10dp"app:layout_constraintEnd_toEndOf="parent"app:layout_constraintStart_toStartOf="parent"app:layout_constraintTop_toBottomOf="@+id/nobutton" /></androidx.constraintlayout.widget.ConstraintLayout>

使用安科(来自静态编程语言开发人员的官方库),您可以简单地使用

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"

在过去的几天里,我的同事一直在问我关于在Xamarin.Android中使用AlertDialog的问题,几乎所有人都把这个问题作为他们在问我之前阅读的参考(没有找到答案),所以这里是Xamarin.AndroidC#)版本:

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 sovar tvMessage = alertDialog.FindViewById<TextView>(Android.Resource.Id.Message);tvMessage.TextSize = 13;// ...
    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() {@Overridepublic 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();

Kotln开发人员最简单的解决方案

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

静态编程语言自定义对话框:如果您想创建自定义对话框

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.zval 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 hereval 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中创建LoadingIndex atorDialogStyle

<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>-->

使用材料组件库,您可以使用#0

   MaterialAlertDialogBuilder(context).setMessage("Are you sure you want to delete this entry?").setPositiveButton("Delete") { dialog, which ->// Respond to positive button press}.setNegativeButton("Cancel") { dialog, which ->// Respond to positive button press}.show()

在此处输入图片描述

使用组成1.0.x,您可以使用:

val openDialog = remember { mutableStateOf(true) }
if (openDialog.value) {AlertDialog(onDismissRequest = {// Dismiss the dialog when the user clicks outside the dialog or on the back// button. If you want to disable that functionality, simply use an empty// onCloseRequest.openDialog.value = false},title = null,text = {Text("Are you sure you want to delete this entry?")},confirmButton = {TextButton(onClick = {openDialog.value = false}) {Text("Delete")}},dismissButton = {TextButton(onClick = {openDialog.value = false}) {Text("Cancel")}})}

在此处输入图片描述

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

现在在android中引入了jetpack合成,您可以使用以下代码简单地创建警报对话框

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 = falseviewModel.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/

试试这个静态编程语言

AlertDialog.Builder(this).setTitle("Title").setPositiveButton("Yes"){ dialog, which ->
}.setNegativeButton("No", null).setMessage("Your given alert message...").show()