在AlertDialog中更改OK按钮的颜色

时间:2018-04-03 11:40:56

标签: android kotlin alertdialog android-textinputlayout

我试图更改Android中button中正面AlertDialog的颜色。原本在我的S8上,按钮是绿色的,但是当我尝试更换它时,无论我选择什么颜色,它都会变成亮紫色。(我已尝试过许多不同深浅的蓝色甚至是粉红色来测试)

我用以下方式更改颜色:

dialog.getButton(DialogInterface.BUTTON_POSITIVE).textColor = R.color.color_blue

我在dialog.show()之后调用它。

4 个答案:

答案 0 :(得分:1)

尝试以下方式,您可能会得到解决方案

dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(neededColor);
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(neededColor);

答案 1 :(得分:1)

我宁愿使用theme来控制对话框的样子。在你的情况下

R.color.color_blue 是一个res id。您必须将其转换为颜色。例如

 dialog.getButton(DialogInterface.BUTTON_POSITIVE).textColor = ContextCompat.getColor(this, R.color.color_blue)

答案 2 :(得分:0)

您可以先尝试创建AlertDialog对象,然后使用它来设置更改按钮的颜色然后显示它。 (请注意,在builder对象上,而不是调用show(),我们调用create()来获取AlertDialog对象:

//1. create a dialog object 'dialog'
MyCustomDialog builder = new MyCustomDialog(getActivity(), "Try Again", errorMessage); 
AlertDialog dialog = builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialogInterface, int i) {
                    ...
                }

            }).create();

//2. now setup to change color of the button
dialog.setOnShowListener( new OnShowListener() {
    @Override
    public void onShow(DialogInterface arg0) {
        dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(COLOR_I_WANT);
    }
});

dialog.show()

您必须在onShow()上执行此操作并且在创建对话框后无法获取该按钮的原因是该按钮尚未创建。

我将AlertDialog.BUTTON_POSITIVE更改为AlertDialog.BUTTON_NEGATIVE以反映您问题的变化。虽然很奇怪“OK”按钮会是一个负面按钮。通常它是正面按钮。

答案 3 :(得分:0)

您可以为提醒对话设置自定义主题

<style name="AlertDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:colorPrimary">#FFFFFF</item>
    <item name="android:textColorPrimary">#FFFFFF</item>
    <item name="android:colorAccent">#FFFFFF</item>
    <item name="colorPrimaryDark">#FFFFFF</item>
</style>

根据您的选择设置颜色

相关问题