【问题标题】:How to make AlertDialog custom buttons android?如何使 AlertDialog 自定义按钮 android?
【发布时间】:2016-04-11 20:55:15
【问题描述】:

我有一个警报对话框,目前看起来像这样: Current Alert Dialog

但我希望“YES”和“NO”按钮有背景,或者看起来像按钮而不是文本。我尝试为 AlertDialog 实现自定义主题,但我能得到的唯一更改是更改“警告”文本颜色。

自定义警报对话框的主题以使用实际按钮代替“YES”和“NO”的最有效和最简单的方法是什么?

这是我当前的 res/values/styles.xml 文件

<resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light">
    <!-- Customize your theme here. -->
    <item name="colorAccent">@color/PCCA_blue</item>
</style>

<style name="customAlertDialog" parent="@android:style/Theme.Holo.Dialog">
    <item name="android:textColor">@color/red</item>

 </style>

这就是我构建和显示 AlertDialog 的地方:

private void alert(final String action){
    final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(new ContextThemeWrapper(this, R.style.customAlertDialog));
    String message = "";

    switch(action) {
        case "upload":
            message = "Are you sure you want to upload the counted quantities?\n\nIt may take a few minutes to reflect your changes.";
            break;
        case "download":
            message = "Downloading new worksheets may overwrite existing counted quantities, do you want to continue?\n\n" +
                    "NOTE: You may want to upload counts first.\n\n" +
                    "(Changed counted quantities will still be available for upload)";
            break;
        default:
            message = action;
            break;
    }


    alertDialogBuilder.setTitle("WARNING");
    alertDialogBuilder.setMessage(message);
    DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            if(which == DialogInterface.BUTTON_POSITIVE) {
                if (action.equals("upload")) {
                    MainActivity.upload(context);
                } else if (action.equals("download")) {
                    MainActivity.download(context);
                }
            } else {
                dialog.cancel();
            }
        }
    };

    alertDialogBuilder.setPositiveButton("YES", listener);
    alertDialogBuilder.setNegativeButton("NO", listener);

    AlertDialog alertDialog = alertDialogBuilder.create();
    alertDialog.show();

}

感谢任何建议。我是安卓新手。

【问题讨论】:

  • 您可以创建自己的布局并将其设置为对话框的视图。这需要更多的工作和设置,但这是我知道的唯一方法。
  • setView() 用于对话框的主体,而不是按钮。

标签: android android-alertdialog android-styles


【解决方案1】:

AlertDialog 有一个getButton() 方法。您可以获取按钮并将其设置为背景。有一些注意事项:您只能在显示对话框后调用该方法(我相信在 Dialog 类上调用了onStart() 之后)。

话虽如此,考虑到填充、边距、包含布局等,您可能无法获得您想要的外观。AlertDialog 的重点是要有一个与系统主题相匹配的标准外观对话框。它并不意味着可定制,UI 方面。

否则,您需要创建一个完全自定义的对话框。您有几个选项:DialogFragment、自定义 Dialog 或以对话框为主题的活动。谷歌这些主题以获取更多信息。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 2011-08-14
    • 2016-09-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多