我想显示一个对话框/弹出窗口,并向用户显示“您确定要删除此条目吗?”的消息。 一个带有“删除”按钮。 触摸Delete ,它应删除该条目,否则不删除任何条目。

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


#1楼

试试这个代码:

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

#2楼

您可以使用以下代码:

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 dialogToast.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 dialogToast.makeText(getApplicationContext(),"You clicked on NO", Toast.LENGTH_SHORT).show();dialog.cancel();}});// Showing Alert Dialog
alertDialog2.show();

#3楼

这绝对对您有帮助。 尝试以下代码:单击按钮时,可以将一个,两个或三个按钮与警报对话框一起放置...

SingleButtton.setOnClickListener(new View.OnClickListener() {public void onClick(View arg0) {// Creating alert Dialog with one ButtonAlertDialog 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 ButtonsAlertDialog.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 ButtonsAlertDialog.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();}
});

#4楼

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

#5楼

我创建了一个对话框,询问一个人是否要呼叫一个人。

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

#6楼

如今,最好使用DialogFragment而不是直接创建AlertDialog。

  • 怎么样? 参见: https : //stackoverflow.com/a/21032871/1390874
  • 为什么? 参见: https : //stackoverflow.com/a/13765411/1390874

#7楼

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

#8楼

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

#9楼

只是一个简单的! 创建一个对话框方法,在您的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"?>
<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使用文本和颜色。 您可以定义自己的。


#10楼

要关闭对话框时请小心,请使用dialog.dismiss() 。 在我的第一次尝试中,我使用了dismissDialog(0) (我可能是从某个地方复制的), 有时可以工作。 使用该对象,系统提供的声音听起来是一个更安全的选择。


#11楼

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

private void showDialog()
{String text2 = "<font color=#212121>Medi Notification</font>";//for custom title colorAlertDialog.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();
}

#12楼

import android.app.*;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.*;public class ShowPopUp extends Activity {PopupWindow popUp;
LinearLayout layout;
TextView tv;
LayoutParams params;
LinearLayout mainLayout;
Button but;
boolean click = true;public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);popUp = new PopupWindow(this);layout = new LinearLayout(this);mainLayout = new LinearLayout(this);tv = new TextView(this);but = new Button(this);but.setText("Click Me");but.setOnClickListener(new OnClickListener() {public void onClick(View v) {if (click) {popUp.showAtLocation(mainLayout, Gravity.BOTTOM, 10, 10);popUp.update(50, 50, 300, 80);click = false;} else {popUp.dismiss();click = true;}}});params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);layout.setOrientation(LinearLayout.VERTICAL);tv.setText("Hi this is a sample text for popup window");layout.addView(tv, params);popUp.setContentView(layout);// popUp.showAtLocation(layout, Gravity.BOTTOM, 10, 10);mainLayout.addView(but, params);setContentView(mainLayout);}}

#13楼

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上的Dialogs上的博客,您会在这里找到所有详细信息: http : //www.fahmapps.com/2016/09/26/dialogs-in-android-part1/ 。


#14楼

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

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


#15楼

你可以试试这个。

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

有关更多信息,请检查此链接...


#16楼

为了我

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

#17楼

试试这个代码

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

#18楼

   new AlertDialog.Builder(v.getContext()).setMessage("msg to display!").show();

#19楼

您可以使用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.show();

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


#20楼

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

#21楼

使用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() {@Overridepublic void onClick(DialogInterface dialogInterface, int i) {//set what would happen when positive button is clicked    finish();}
})
//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警报对话框教程


#22楼

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

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

通过Buttons和TextViews对其进行充气

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

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

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

#23楼

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
}

爪哇

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

#24楼

我想通过分享一种比他发布的动态方法更多的动态方法来为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 herebreak;//TODO: add cases when needed}}});}builder.setIcon(android.R.drawable.ic_dialog_alert);builder.show();
}

#25楼

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

这种方法类似于用一些代码行创建“警报”对话框。


#26楼

从列表中删除条目的代码

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

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


#27楼

这是在科特林完成的

    var 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 Entry").setMessage("Are you want to delete this entry").setPositiveButton("Yes") {}.setNegativeButton("No"){}.setIcon(R.drawable.ic_launcher_foreground).show()

#28楼

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

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

#29楼

制作此静态方法,并在任何需要的地方使用它。

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

#30楼

我在按钮onclick方法中使用了此alart对话框。

        button.setOnClickListener(v -> {AlertDialog.Builder builder = new AlertDialog.Builder(this);LayoutInflater layoutInflaterAndroid = LayoutInflater.from(this);View view2 = layoutInflaterAndroid.inflate(R.layout.cancel_dialog, null);builder.setView(view2);builder.setCancelable(false);final AlertDialog alertDialog = builder.create();alertDialog.show();view2.findViewById(R.id.yesButton).setOnClickListener(v1 -> onBackPressed());view2.findViewById(R.id.nobutton).setOnClickListener(v12 -> 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>

#31楼

使用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"

如何在Android上显示警报对话框?相关推荐

  1. android 显示进度,progressdialog-如何在Android中显示进度对话框?

    progressdialog-如何在Android中显示进度对话框? 当我单击"登录"按钮时,我想显示ProgressDialog,这需要时间才能移动到另一个页面. 我怎样才能做到 ...

  2. 如何在Android上显示wmf的文件

    菜鸟进场,方圆十里,寸草不生 最近定制化一个app,需要显示wmf的文件,但是Android上无法对这种文件的直接显示,所以就需要对文件进行一个转换,网上对这方面的需求很少,所以简单的记录一下,就讲讲 ...

  3. android 工作日,如何在Android上重复警报工作日

    小编典典 请尝试此代码.已在我的应用中成功运行 if (chk_monday.isChecked()) { forday(2); } else if (chk_tuesday.isChecked()) ...

  4. android 泰文ttf字体,如何在Android上正确显示泰语diactirics?

    简短的序言.泰语字母有可能出现在辅音上方的元音符号,并且在辅音上方也存在变音符号(DS).当元音和DS出现时,它们出现一个在另一个之上,所以元音被设置在辅音之上并且DS被设置在元音之上.如何在Andr ...

  5. android用对话框捕捉异常,Android - 在捕获异常时在doinbackground期间显示警报对话框...

    我有这个代码,只要它碰到Source.httpConn就会捕获它,它发送下面的异常来捕获.Android - 在捕获异常时在doinbackground期间显示警报对话框 try { JSONToke ...

  6. 如何在android中创建自定义对话框?

    本文翻译自:How to create a Custom Dialog box in android? I want to create a custom dialog box like below ...

  7. android 设置对话框的高度,如何控制Android中默认警报对话框的宽度和高度?

    如何控制Android中默认警报对话框的宽度和高度?AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setTi ...

  8. 最近朋友圈晒足迹足迹刷屏_如何在Android上使用私人浏览隐藏您的足迹

    最近朋友圈晒足迹足迹刷屏 Private browsing allows you to surf the web without saving any information about your b ...

  9. win10显示隐藏文件_如何在Mac上显示隐藏文件?苹果mac显示隐藏文件夹方法

    与任何操作系统一样,macOS会将重要文件隐藏起来,以防止意外删除它们并因此而损坏系统.但是,在某些情况下,您可能需要在Mac上显示隐藏文件,例如,浏览" 库"文件夹并清除旧日志, ...

最新文章

  1. Sequence在Oracle中的使用
  2. VTK:Filtering之WarpTo
  3. 好长时间没有到博客园来看看了
  4. 文献记录(part59)--多任务学习
  5. 为什么jdk的CLASSPATH环境变量需要设置rt.jar 和 tools.jar
  6. [vue] 在组件中怎么访问到根实例?
  7. 如何通过一个结构体成员变量的地址找到该结构体的首地址?[备忘]
  8. C#/.net 中的事件与代理
  9. python语言的读法-Python语言的优势有哪些?
  10. 如何使用TunesKit AceMovi Video Editor Mac在视频中添加贴纸
  11. JVM - 类加载器
  12. 耳目一新的汇小贷P2P网贷加盟连锁优势
  13. 用Python实现一个商场管理系统(附源码)
  14. cdh 6.x、cdh 5.16.x、cdh 5.15.x、cdh 5.14.x、cdh 5.12.x组件对应版本
  15. TCP合法RST报文
  16. torch.randn()用法
  17. STM32用ST-link下载程序
  18. Access数据库文件HeroDB.MDB用什么工具可以打开呢?
  19. Jenkins测试报告邮件发送
  20. 【音视频】使用FFMPEG进行RTSP|RTMP|HLS推流(3-3)

热门文章

  1. swift闭包的另一种用法
  2. javascript(jQuery版)切换tab效果自动切换(转自www.jqueryba.com)
  3. Linux下的 API Hook
  4. Windows7快捷键大全
  5. Java工程师成神之路思维导图
  6. Android Theme主题
  7. mongo数据排序和分页显示
  8. C# ASP.NET 转换为int型的方法 很实用
  9. 第一个简单APP设计图
  10. Oracle在Linux内核参数的修改