如何在Android中制作自定义按钮的AlertDialog?

3
我有一个警告对话框,目前看起来像这样:当前警告对话框 但我希望"Yes"和"No"按钮有背景,或者看起来像按钮而不仅仅是文本。我尝试实现AlertDialog的自定义主题,但我能够做出的唯一改变是改变“WARNING”文字颜色。
最有效和简单的方法是什么,以定制警告对话框的主题,以便在"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();

}

任何建议都受到赞赏。我是Android新手。

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

1

AlertDialog有一个getButton()方法。你可以获取按钮并设置它的背景。但需要注意一些事项:只有在对话框显示后(我相信在Dialog类的onStart()被调用后)才能调用该方法。

话虽如此,考虑到填充、边距、包含布局等因素,很可能无法获得所需的外观。AlertDialog的目的是具有与系统主题相匹配的标准外观。从UI角度来看,它不是可定制的。

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接