【问题标题】:How do I display an alert dialog on Android?如何在 Android 上显示警报对话框?
【发布时间】:2011-01-08 02:46:14
【问题描述】:

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

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

【问题讨论】:

标签: android android-alertdialog android-dialog


【解决方案1】:

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

【讨论】:

  • 不应该将AlertDialog.Builder(this) 替换为AlertDialog.Builder(className.this) 吗?
  • 不一定。如果您从某个侦听器构建警报对话框,则需要它。
  • 请记住 AlertDialog.Builder 不能通过 dismiss() 方法关闭。您也可以使用 AlertDialog dialog = new AlertDialog.Builder(context).create();你就可以正常调用dismiss()了。
  • 抽屉项目选择不起作用,但这个起作用:stackoverflow.com/a/26097588/1953178
  • 不是真的@Fustigador
【解决方案2】:

试试这个代码:

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

【讨论】:

  • +1。这是一种更好的方法。 @Mahesh 创建了对话框的一个实例,因此cancel() 等可以访问它。
  • 是否需要builder1.create(),因为当您直接调用builder1.show() 时它似乎工作正常?
  • @razzak 是的,这是必要的,因为它为我们提供了对话框实例。我们可以使用对话框实例来访问特定于对话框的方法
  • 我正在尝试这种方法,但是警报窗口弹出并立即消失,没有让我有时间阅读它。我显然也没有时间单击按钮将其关闭。知道为什么吗?
  • 没关系,我找到了原因,我正在触发一个新的 Intent 并且它没有等待我的警报窗口弹出,我可以在这里找到:stackoverflow.com/questions/6336930/…
【解决方案3】:

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

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

如果您遇到同样的错误,请使用以下代码。有效!!

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

【讨论】:

  • 我们不需要同时使用create()show(),因为show() 已经创建了包含所描述内容的对话框。根据文档,create() 使用提供给此构建器的参数创建一个 AlertDialog。它不是 Dialog.show() 对话框。这允许用户在显示对话框之前进行任何额外的处理。 如果您没有任何其他处理要做并希望创建和显示它,请使用 show()。 因此,只有在您计划使用 create() 时才有用稍后显示对话框,并且您正在提前加载其内容。
  • 将参数从 getApplicationContext() 更改为 MyActivity.this 并开始工作。
【解决方案4】:

使用 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() {
    @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 Alert Dialog Tutorial

【讨论】:

    【解决方案5】:

    只是一个简单的!在 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 XML dialog_demo.xml 并创建您的 UI/设计。这是我为演示目的创建的示例:

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

    现在你可以在任何你喜欢的地方拨打openDialog() :) 这是上面代码的截图。

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

    【讨论】:

    • Dialog 类是对话框的基类,但您应该避免直接实例化 Dialog。相反,请使用以下子类之一:AlertDialog, DatePickerDialog or TimePickerDialog(来自 developer.android.com/guide/topics/ui/dialogs.html
    • 这里不能点击“取消”和“同意”。
    【解决方案6】:

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

    【讨论】:

    • 另外,我在使用自定义内容视图填充奇怪的系统 AlertDialog 背景时遇到了很多麻烦。
    【解决方案7】:

    您可以使用此代码:

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

    【讨论】:

    • dialog.cancel();不应在第二个侦听器中调用
    • “本教程”链接已损坏。它带你到“store.hp.com/…
    【解决方案8】:

    对我来说

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

    【讨论】:

      【解决方案9】:
      new AlertDialog.Builder(context)
          .setTitle("title")
          .setMessage("message")
          .setPositiveButton(android.R.string.ok, null)
          .show();
      

      【讨论】:

        【解决方案10】:
        // 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();
        }
        

        【讨论】:

        • 您的代码不正确,需要将 setPositiveButton("cancel" 改为 setNegativeButton("cancel"
        • 谢谢,这是错误发生的......实际上我想检查是否任何人都可以深入检查发布的代码。而你就是那个......再次感谢......
        【解决方案11】:

        这是一个如何创建Alert Dialog 的基本示例:

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

        【讨论】:

          【解决方案12】:
          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;
          }
          

          【讨论】:

            【解决方案13】:

            这绝对对你有帮助。试试这个代码:点击一个按钮,你可以放一个、两个或三个带有警报对话框的按钮......

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

            【讨论】:

              【解决方案14】:

              我创建了一个对话框,用于询问 Person 是否要调用 Person。

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

              【讨论】:

                【解决方案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() {
                    @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();
                

                For more info,check this link...

                【讨论】:

                  【解决方案16】:

                  试试这个代码

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

                  【讨论】:

                    【解决方案17】:

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

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

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

                    【讨论】:

                      【解决方案18】:

                      通过材料组件库,您只需使用 MaterialAlertDialogBuilder

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

                      使用 Compose 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")
                                  }
                              }
                          )
                      }
                      

                      【讨论】:

                        【解决方案19】:
                           new AlertDialog.Builder(v.getContext()).setMessage("msg to display!").show();
                        

                        【讨论】:

                        • 请解释
                        • 请不要解释。这个答案是完美的,任何试图添加文字来安抚“请解释”机器人都会使情况变得更糟。
                        【解决方案20】:

                        我在按钮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">
                        
                        <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>
                        

                        【讨论】:

                        • 请更新提供的代码,并解释它的确切作用。
                        【解决方案21】:

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

                        【讨论】:

                          【解决方案22】:

                          我想通过分享一种比他发布的方法更动态的方法来补充 David Hedlund 的好答案,以便在您确实需要执行负面操作时使用它,而当您没有执行操作时,我希望它有所帮助。

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

                          【讨论】:

                            【解决方案23】:

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

                            【讨论】:

                              【解决方案24】:
                              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/

                              【讨论】:

                                【解决方案25】:

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

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

                                【讨论】:

                                  【解决方案26】:

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

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

                                  【讨论】:

                                    【解决方案27】:

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

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

                                    【讨论】:

                                      【解决方案28】:

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

                                      【讨论】:

                                        【解决方案29】:
                                        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();
                                        

                                        这是一种类似用几行代码创建警报对话框的方式。

                                        【讨论】:

                                          【解决方案30】:

                                          从列表中删除条目的代码

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

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

                                          【讨论】:

                                            猜你喜欢
                                            • 2023-03-05
                                            • 1970-01-01
                                            • 1970-01-01
                                            • 1970-01-01
                                            • 1970-01-01
                                            • 2021-03-08
                                            • 1970-01-01
                                            • 1970-01-01
                                            相关资源
                                            最近更新 更多