Android 更改AlertDialog中“确定”按钮的颜色

Android 更改AlertDialog中“确定”按钮的颜色,android,kotlin,android-alertdialog,android-textinputlayout,Android,Kotlin,Android Alertdialog,Android Textinputlayout,我正试图在Android中的警报对话框中更改肯定的按钮的颜色。S8上的按钮本来是绿色的,但当我尝试改变它时,无论我选择什么颜色,它都会变成明亮的紫色。(我试过许多不同深浅的蓝色,甚至粉色来测试) 我正在使用以下选项更改颜色: dialog.getButton(DialogInterface.BUTTON_POSITIVE).textColor = R.color.color_blue 我在对话框后调用它。show()尝试以下方法,您可能会得到您的解决方案 dialog.getButton(Al

我正试图在Android中的
警报对话框
中更改肯定的
按钮
的颜色。S8上的按钮本来是绿色的,但当我尝试改变它时,无论我选择什么颜色,它都会变成明亮的紫色。(我试过许多不同深浅的蓝色,甚至粉色来测试)

我正在使用以下选项更改颜色:

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

我在
对话框后调用它。show()

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

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

我宁愿使用
主题
来控制对话框的外观。就你而言

R.color.color\u蓝色是一个分辨率id。您必须将其转换为颜色。乙二醇


您可以尝试先创建
AlertDialog
对象,然后使用它进行设置以更改按钮的颜色,然后显示它。(注意,在
builder
对象上,我们调用
create()
而不是调用
show()
来获取
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\u POSITIVE
更改为
AlertDialog.BUTTON\u NEGATIVE
以反映问题中的更改。虽然奇怪的是,“OK”按钮将是一个否定按钮。通常是肯定按钮。

您可以为AlertDialog设置自定义主题


#FFFFFF
#FFFFFF
#FFFFFF
#FFFFFF

根据您的选择设置颜色。

我认为对话框文本颜色是根据应用程序主题设置的,如果不更改Colors.xml中的主题强调颜色,则无法更改它
//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()
<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>