【问题标题】:How to implement an alert dialog in androidX [duplicate]如何在androidX中实现警报对话框[重复]
【发布时间】:2020-01-18 13:02:45
【问题描述】:

我已将我的项目迁移到 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:您需要在此活动中使用 Theme.AppCompat 主题(或后代)。

【问题讨论】:

    标签: java android android-alertdialog androidx material-components-android


    【解决方案1】:

    您可以使用Material Components library提供的MaterialAlertDialogBuilder

    只需使用:

    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

    【讨论】:

    • 谢谢,我会试一试的。
    猜你喜欢
    • 2018-05-10
    • 1970-01-01
    • 1970-01-01
    • 2018-08-27
    • 2017-09-14
    • 2014-11-23
    • 2013-06-26
    • 2023-03-25
    • 2018-03-05
    相关资源
    最近更新 更多