如何在androidX中实现一个警告对话框

How to implement an alert dialog in androidX

我已经将我的项目迁移到 androidX,我想实现一个带有用户正面和负面反馈的警告对话框。

我正在使用这个代码:

AlertDialog.Builder builder1 = new AlertDialog.Builder(getApplicationContext());

               builder1.setMessage("Write your message here.");
               builder1.setCancelable(true);

               builder1.setPositiveButton(
                       "Yes",
                       new DialogInterface.OnClickListener() {
                           public void onClick(DialogInterface dialog, int id) {

                               Log.d("MSG", "onClick: YES");
                           }
                       });

               builder1.setNegativeButton(
                       "No",
                       new DialogInterface.OnClickListener() {
                           public void onClick(DialogInterface dialog, int id) {
                               dialog.cancel();
                               Log.d("MSG", "onClick: No");

                           }
                       });

               AlertDialog alert11 = builder1.create();
               alert11.show();

但是当 运行 应用程序时出现此错误:

java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

您可以使用 MaterialAlertDialogBuilder provided by the Material Components library.

只需使用:

new MaterialAlertDialogBuilder(context)
            .setTitle("Dialog")
            .setMessage("Write your message here. ....")
            .setPositiveButton("Ok", /* listener = */ null)
            .setNegativeButton("Cancel", /* listener = */ null)
            .show();

MaterialAlertDialogBuilder 需要一个 Material 主题,并且会产生一个 androidx.appcompat.app.AlertDialog