如何在安卓5中更改默认对话框按钮文本颜色

214

我在我的应用程序中有许多警报对话框。它是默认布局,但我正在向对话框添加积极和消极按钮。因此,按钮获得Android 5的默认文本颜色(绿色)。我尝试过更改它,但没有成功。有什么办法可以更改那个文本颜色吗?

我的自定义对话框:

public class MyCustomDialog extends AlertDialog.Builder {

    public MyCustomDialog(Context context,String title,String message) {
        super(context);

        LayoutInflater inflater = (LayoutInflater) context.getSystemService( Context.LAYOUT_INFLATER_SERVICE );
        View viewDialog = inflater.inflate(R.layout.dialog_simple, null, false);

        TextView titleTextView = (TextView)viewDialog.findViewById(R.id.title);
        titleTextView.setText(title);
        TextView messageTextView = (TextView)viewDialog.findViewById(R.id.message);
        messageTextView.setText(message);

        this.setCancelable(false);

        this.setView(viewDialog);

    } }

创建对话框:

MyCustomDialog builder = new MyCustomDialog(getActivity(), "Try Again", errorMessage);
builder.setNegativeButton("OK", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            ...
                        }
}).show();

那个 negativeButton 是一个默认的对话框按钮,它会从 Android 5 Lollipop 中获取默认的绿色。

非常感谢

带有绿色按钮的自定义对话框


几乎是重复的问题/答案https://dev59.com/6F8d5IYBdhLWcg3wxUjC#29810469,我觉得现在更适用。 - Jon Adams
18个回答

396

以下是一种使用样式的自然方法:

如果您的AppThemeTheme.MaterialComponents继承,则:

<style name="AlertDialogTheme" parent="ThemeOverlay.MaterialComponents.Dialog.Alert">
    <item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
    <item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
</style>

<style name="NegativeButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
    <item name="android:textColor">#f00</item>
</style>

<style name="PositiveButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
    <item name="android:textColor">#00f</item>
</style>

如果您的AppTheme是从Theme.AppCompat继承而来:

<style name="AlertDialogTheme" parent="ThemeOverlay.AppCompat.Dialog.Alert">
    <item name="buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
    <item name="buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
</style>

<style name="NegativeButtonStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
    <item name="android:textColor">#f00</item>
</style>

<style name="PositiveButtonStyle" parent="Widget.AppCompat.Button.ButtonBar.AlertDialog">
    <item name="android:textColor">#00f</item>
</style>

在您的AppTheme中使用您的AlertDialogTheme

<item name="alertDialogTheme">@style/AlertDialogTheme</item>

或在构造函数中

androidx.appcompat.app.AlertDialog.Builder(context, R.style.AlertDialogTheme)

或者,如果您正在使用MaterialAlertDialogBuilder,则使用

<item name="materialAlertDialogTheme">@style/AlertDialogTheme</item>

55
我不得不将buttonBarNegativeButtonStyle更改为android:buttonBarNegativeButtonStyle,将buttonBarPositiveButtonStyle更改为android:buttonBarPositiveButtonStyle。然后它可以正常工作(API 21+)。 - Vlad
34
请记得使用android.support.v7.app.AlertDialog而不是android.app.AlertDialog。无意义的错误让我浪费了2小时。 - thanhbinh84
2
我不得不将AlertDialogTheme的父级更改为"Base.Theme.AppCompat.Light.Dialog.Alert"。并删除buttonBarNegativeButtonStyle和buttonBarPositiveButtonStyle。还在AlertDialogTheme中添加<item name="colorAccent">@color/dashboard_red_color</item>。现在它完美地工作了。 - zephyr
4
使用新的材料库com.google.android.material:material:1.0.0-beta01时,这不起作用,而我正在使用Theme.MaterialComponents.Light.Dialog.Alert。 - Sanjeev
2
对于 Android 的 Material 组件,<item name="alertDialogTheme">@style/AlertDialogTheme</item> 应该改为 <item name="materialAlertDialogTheme">@style/AlertDialogTheme</item> - Rafa Viotti
显示剩余13条评论

242

您可以先尝试创建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以反映问题的更改。虽然“确定”按钮成为负面按钮很奇怪。通常它是正面的按钮。


谢谢您的回答,但是在AlertDialog中我没有那个方法。请看我的更新帖子。 - FOMDeveloper
5
这个方法在AlertDialog类中,不在Builder类中。所以不要调用Builder.show(),而是使用Builder.create()来返回AlertDialog类。然后设置监听器并在AlertDialog对象上调用show()。 - trungdinhtrong
4
有另一种方式可以做到这一点。似乎这是主题中的颜色,我们能否通过主题/样式来更改它? - milosmns
这太完美了。我刚在Xamarin.Android中尝试了一下,它完美地工作了。非常感谢你。 - gregoryp

130
按钮和其他文本的颜色也可以通过主题进行更改:

values-21/styles.xml

<style name="AppTheme" parent="...">
  ...
  <item name="android:timePickerDialogTheme">@style/AlertDialogCustom</item>
  <item name="android:datePickerDialogTheme">@style/AlertDialogCustom</item>
  <item name="android:alertDialogTheme">@style/AlertDialogCustom</item>
</style>

<style name="AlertDialogCustom" parent="android:Theme.Material.Light.Dialog.Alert">
  <item name="android:colorPrimary">#00397F</item>
  <item name="android:colorAccent">#0AAEEF</item>
</style>

结果:

对话框 日期选择器


1
目前我不知道如何仅更改复选框颜色或按钮颜色。强调色会同时更改它们的颜色。 - peceps
4
我喜欢这种方法,但我觉得https://dev59.com/6F8d5IYBdhLWcg3wxUjC#29810469上的答案是一种更加简洁的方式来实现它。 - Jon Adams
18
为了让我的项目正常运行,我需要从android:alertDialogThemeandroid:colorAccent中删除 android: 部分。 - ban-geoengineering
2
在values或values-vXX中放置styles.xml取决于值是否具有android:前缀。 - peceps
1
要使其与AppCompat和简单的values文件夹配合使用,只需按照@ban-geoengineering建议的更改进行即可。 - Felix
显示剩余4条评论

119

最简单的解决方案是:

dialog.show(); //Only after .show() was called
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(neededColor);
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(neededColor);

4
这些字段不应该从非静态变量引用,应该是AlertDialog.BUTTON_NEGATIVE等。 - Joe Maher
这是最好、最简单的方法。请注意,我没有使用“create”,而是在show()之后获取了对话框。就像AlertDialog dialog = builder.show();这样。 - Stephen McCormick
2
虽然这个解决方案可能有效,但从逻辑上讲它是有缺陷的。这里发生的情况是你首先显示对话框,然后再改变它的外观。这取决于底层实现(可能随时间而改变)和设备的性能,理论上用户可能会看到一个“闪烁”,即对话框出现然后迅速改变其外观。 - trungdinhtrong

55

更改对话框按钮颜色有两种方法。

基本方式

如果您只想在一个活动中进行更改,请在 alertDialog.show(); 后写下以下两行:

alertDialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.colorPrimary));
alertDialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.colorPrimaryDark));

推荐

我建议在 styles.xml 中为 AlertDialog 添加一个主题,这样你就不必在每个活动或对话框调用中反复编写相同的代码。你可以创建一个样式并将其应用到对话框上。因此,当你想要更改 AlertDialog 对话框的颜色时,只需在 styles.xml 中更改颜色即可,整个应用程序中所有的对话框都会更新。

<style name="AlertDialogTheme" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="colorAccent">@color/colorPrimary</item>
</style>

AlertDialog.Builder中应用主题。

AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AlertDialogTheme);

2
这个答案是最干净的,同时仍然是正确的。 - Big_Chair
工作了!太棒了... - Fahmi Eshaq

18
  1. 在您的应用程序主题/样式中,添加以下行:

<item name="android:buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
<item name="android:buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
<item name="android:buttonBarNeutralButtonStyle">@style/NeutralButtonStyle</item>
  • 然后添加以下样式:

  • <style name="NegativeButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
        <item name="android:textColor">@color/red</item>
    </style>
    
    <style name="PositiveButtonStyle" parent="Widget.MaterialComponents.Button.TextButton.Dialog">
        <item name="android:textColor">@color/red</item>
    </style>
    
    <style name="NeutralButtonStyle" 
    parent="Widget.MaterialComponents.Button.TextButton.Dialog">
        <item name="android:textColor">#00f</item>
    </style>
    
    使用这种方法可以避免在AlertDialog构建器中设置主题。

    你应用了哪个主题? - Bad Loser

    13

    如果你想要改变按钮的文字颜色(积极,消极,中立),只需在自定义对话框样式中添加:

    <item name="colorAccent">@color/accent_color</item>
    

    所以,你的对话风格必须是这样的:

    <style name="AlertDialog" parent="Theme.AppCompat.Light.Dialog.Alert">
        <item name="android:textColor">@android:color/black</item>
        <item name="colorAccent">@color/topeka_accent</item>
    </style>
    

    10

    Kotlin 2020:非常简单的方法

    dialog.show()之后使用:

    dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(ContextCompat.getColor(requireContext(), R.color.yourColor))
    

    7
    我们可以创建扩展函数,并在dialog.show()之后调用扩展函数来自定义警报对话框按钮颜色。
    fun AlertDialog.makeButtonTextBlue() {
    this.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(context, R.color.blue))
    this.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(ContextCompat.getColor(context, R.color.blue))
    }
    

    使用方法:

    dialog.show()
    dialog.makeButtonTextBlue()
    

    7

    以下是如何进行操作:简单方法

    // Initializing a new alert dialog
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setMessage(R.string.message);
    builder.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            doAction();
        }
    });
    builder.setNegativeButton(R.string.cancel, null);
    
    // Create the alert dialog and change Buttons colour
    AlertDialog dialog = builder.create();
    dialog.setOnShowListener(new DialogInterface.OnShowListener() {
        @Override
        public void onShow(DialogInterface arg0) {
            dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(getResources().getColor(R.color.red));
            dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(getResources().getColor(R.color.blue));
            //dialog.getButton(AlertDialog.BUTTON_NEUTRAL).setTextColor(getResources().getColor(R.color.black));
        }
    });
    dialog.show();
    

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