How do I display an alert dialog on Android?
我想显示一个对话框/弹出窗口,并向用户显示一条消息:"您确定要删除此条目吗?"一个按钮上写着"删除"。当触摸
我已经为这些按钮编写了一个点击监听器,但是如何调用对话框或弹出窗口及其功能?
您可以为此使用一个
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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(); |
试试这个代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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(); |
大卫·赫德隆德发布的代码给了我一个错误:
Unable to add window — token null is not valid
如果出现相同的错误,请使用以下代码。它起作用了!!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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(); } } }); |
只是一个简单的!在Java类中的任何地方创建一个类似的对话框方法:
1 2 3 4 5 6 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 | <?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> |
现在您可以从任何您喜欢的地方调用
请注意,文本和颜色是从
现在最好使用dialogfragment而不是直接创建alertdialog。
- 怎样?请参阅:https://stackoverflow.com/a/21032871/1390874
- 为什么?请参阅:https://stackoverflow.com/a/13765411/1390874
您可以使用此代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 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 2 3 4 5 6 7 8 9 | 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(); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | // 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(); } |
使用AlertDialog.Builder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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警报对话框教程
这是如何创建警报对话框的基本示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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() { @Override public void onClick(DialogInterface dialog, int id) { //Action for"Delete". } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //Action for"Cancel". } }); final AlertDialog alert = dialog.create(); alert.show(); |
这对你绝对有帮助。尝试此代码:单击某个按钮时,可以将一个、两个或三个按钮与警报对话框一起放置…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 | 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 Title alertDialog.setTitle("Alert Dialog"); // Setting Dialog Message alertDialog.setMessage("Welcome to Android Application"); // Setting Icon to Dialog alertDialog.setIcon(R.drawable.tick); // Setting OK Button alertDialog.setButton("OK", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog,int which) { // Write your code here to execute after dialog closed Toast.makeText(getApplicationContext(),"You clicked on OK", Toast.LENGTH_SHORT).show(); } }); // Showing Alert Message alertDialog.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 Title alertDialog.setTitle("Confirm Delete..."); // Setting Dialog Message alertDialog.setMessage("Are you sure you want delete this?"); // Setting Icon to Dialog alertDialog.setIcon(R.drawable.delete); // Setting Positive"Yes" Button alertDialog.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" Button alertDialog.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 Message alertDialog.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 Title alertDialog.setTitle("Save File..."); // Setting Dialog Message alertDialog.setMessage("Do you want to save this file?"); // Setting Icon to Dialog alertDialog.setIcon(R.drawable.save); // Setting Positive Yes Button alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // User pressed Cancel button. Write Logic Here Toast.makeText(getApplicationContext(), "You clicked on YES", Toast.LENGTH_SHORT).show(); } }); // Setting Negative No Button... Neutral means in between yes and cancel button alertDialog.setNeutralButton("NO", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // User pressed No button. Write Logic Here Toast.makeText(getApplicationContext(), "You clicked on NO", Toast.LENGTH_SHORT) .show(); } }); // Setting Positive"Cancel" Button alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // User pressed Cancel button. Write Logic Here Toast.makeText(getApplicationContext(), "You clicked on Cancel", Toast.LENGTH_SHORT).show(); } }); // Showing Alert Message alertDialog.show(); } }); |
1 2 3 4 5 | new AlertDialog.Builder(context) .setTitle("title") .setMessage("message") .setPositiveButton(android.R.string.ok, null) .show(); |
我创建了一个对话框,询问一个人是否想打电话给他。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | 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 { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.first); ImageView imageViewCall = (ImageView) findViewById(R.id.ring_mig); imageViewCall.setOnClickListener(new OnClickListener() { @Override public 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() { @Override public 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() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); builder.show(); } } |
你可以试试这个……
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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() { @Override public void onClick(DialogInterface dialog, int id) { //Action for"Delete". } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //Action for"Cancel". } }); final AlertDialog alert = dialog.create(); alert.show(); |
有关详细信息,请查看此链接…
您可以使用
试试这个:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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() { @Override public void onClick(DialogInterface dialog, int which) { //perform any action Toast.makeText(getApplicationContext(),"Yes clicked", Toast.LENGTH_SHORT).show(); } }); builder.setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //perform any action Toast.makeText(getApplicationContext(),"No clicked", Toast.LENGTH_SHORT).show(); } }); //creating alert dialog AlertDialog alertDialog = builder.create(); alertDialog.show(); |
要更改警报对话框的正按钮和负按钮的颜色,可以在
1 2 | alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.colorPrimary)); alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.colorPrimaryDark)); |
1 | new AlertDialog.Builder(v.getContext()).setMessage("msg to display!").show(); |
我想补充一下大卫·赫德隆德的回答,他分享了一个比他所发表的更动态的方法,这样当你确实要做一个消极的行为,而当你不做的时候,我希望能有所帮助。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 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(); } |
当你想取消对话时要小心点-使用
1 | showDialog(MainActivity.this,"title","message","OK","Cancel", {...}, {...}); |
科特林
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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 } |
爪哇
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | 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; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | Try this code AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder( MainActivity.this); // set title alertDialogBuilder.setTitle("AlertDialog Title"); // set dialog message alertDialogBuilder .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 dialog AlertDialog alertDialog = alertDialogBuilder.create(); // show it alertDialog.show(); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | 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/。
你也可以这样做,它将提供你的材料风格对话框
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | 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(); } |
带有编辑文本的警报对话框
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | 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(); |
创建这个静态方法,并在需要的地方使用它。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | 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(); } |
1 2 3 4 5 6 | 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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 | 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); } } |
从列表中删除条目的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | /*--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(); } |
单击"删除"按钮调用上述方法
这是在科特林做的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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() |
您可以创建活动并扩展AppCompatActivity。然后在清单中放入下一个样式:
1 2 3 | <activity android:name=".YourCustomDialog" android:theme="Theme.AppCompat.Light.Dialog"> </activity> |
通过按钮和文本视图对其进行充气
然后像对话一样使用这个。
例如,在LinearLayout中,我将填写以下参数:
1 2 | android:layout_width="300dp" android:layout_height="wrap_content" |
我在button onclick方法中使用了这个alart对话框。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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()); }); |
对话XML
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 | <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"> <TextView android: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" /> <TextView android: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" /> <TextView android: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" /> <TextView android: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" /> <TextView android: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> |
使用Anko(来自Kotlin开发人员的官方库),您可以简单地使用
1 | alert("Alert title").show() |
或更复杂的:
1 2 3 4 | alert("Hi, I'm Roy","Have you tried turning it off and on again?") { yesButton { toast("Oh…") } noButton {} }.show() |
导入Anko:
1 | implementation"org.jetbrains.anko:anko:0.10.8" |
在过去的几天里,我的同事一直在问我关于在
1 2 3 4 5 6 7 8 9 10 11 12 13 | 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; // ... |