How can I change default dialog button text color in android 5
Asked Answered
C

18

216

I have many alert dialogs in my app. It is a default layout but I am adding positive and negative buttons to the dialog. So the buttons get the default text color of Android 5 (green). I tried to changed it without success. Any idea how to change that text color?

My Custom dialog:

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);

    } }

Creating the dialog:

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

That negativeButton is a default dialog button and takes the default green color from Android 5 Lollipop.

Many thanks

Custom dialog with green button

Cablet answered 15/1, 2015 at 14:29 Comment(1)
Almost duplicate question/answer https://mcmap.net/q/112884/-material-design-not-styling-alert-dialogs that I feel is more applicable these days.Operant
P
243

You can try to create the AlertDialog object first, and then use it to set up to change the color of the button and then show it. (Note that on builder object instead of calling show() we call create() to get the AlertDialog object:

//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()

The reason you have to do it on onShow() and cannot just get that button after you create your dialog is that the button would not have been created yet.

I changed AlertDialog.BUTTON_POSITIVE to AlertDialog.BUTTON_NEGATIVE to reflect the change in your question. Although it is odd that "OK" button would be a negative button. Usually it is the positive button.

Powell answered 15/1, 2015 at 14:40 Comment(4)
Thanks for you answer, but I dont have that method in AlertDialog. See my updated post.Cablet
That method is in AlertDialog class, not Builder class. So instead of calling Builder.show() you can Builder.create(), which returns the AlertDialog class. You then set up the listener and then call show() on the AlertDialog objectPowell
But there must be another way to do this. Seems like it's a color from the theme, can we change it through the theme/style?Imalda
This is perfect. Just tried in Xamarin.Android and it works perfeclty. Thank you very much.Pice
H
398

Here's a natural way to do it with styles:

If your AppTheme is inherited from Theme.MaterialComponents, then:

<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>

If your AppTheme is inherited from 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>

Use your AlertDialogTheme in your AppTheme

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

or in constructor

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

or If you are using MaterialAlertDialogBuilder then use

<item name="materialAlertDialogTheme">@style/AlertDialogTheme</item>
Hardness answered 21/2, 2017 at 17:8 Comment(18)
I had to change buttonBarNegativeButtonStyle to android:buttonBarNegativeButtonStyle and buttonBarPositiveButtonStyle to android:buttonBarPositiveButtonStyle. Then it worked (API 21+).Amylase
Remember to use android.support.v7.app.AlertDialog instead of android.app.AlertDialog. Bullshit mistake took me 2 hoursSagamore
I had to change in AlertDialogTheme's parent to "Base.Theme.AppCompat.Light.Dialog.Alert". And remove buttonBarNegativeButtonStyle & buttonBarPositiveButtonStyle. Also Add in <item name="colorAccent">@color/dashboard_red_color</item> in AlertDialogTheme. nd works perfectly.Tertial
This doesn't work when using new material library com.google.android.material:material:1.0.0-beta01 and I am using Theme.MaterialComponents.Light.Dialog.AlertSerrell
This has to be the selected answer. Just a few things with style. Why should we edit the way we create dialog at all with new listeners and all??Baneful
@L-X updated answer to include material components themeHardness
The only solution I found when using AndroidX was the answer from @Rob on this question: #52830454Downpour
@LeonardoSibela This answer (from Alexander Perfilyev) does work with Android X, using material components themeBerns
@VadimKotov i'm sure it worked for you and a for a whole bunch of people. However, I had a problem, I encountered this exactly same question and for me, Rob's answer on the other question was the solution, so i figured it was worth mentioning for people that, just like me, was not helped by the answers found in this question. I could've probably elaborated more why I comment that, but on that moment, I didn't. But that's why I did it :)Downpour
For Material Components for Android, <item name="alertDialogTheme">@style/AlertDialogTheme</item> should be <item name="materialAlertDialogTheme">@style/AlertDialogTheme</item>.Astonishing
It took me a couple of minutes to find the right spot for the xml code: Everything's in the res\values\styles.xml file, the big style block can be simply copied to the end of the file (but still before </resources>), the item line has to be added to the <style name="AppTheme" parent= part (= base application theme) that's usually at the very top of the file and also includes the e.g. colorPrimary item.Amling
It doesn't work if you are using MaterialComponents Bridge! I spent like an hour thinking I was going crazy!Bartholomeo
this makes texts very tinyAccording
@Amling yeah that's pretty common, I reckon. When we talk about XML styles they're usually places in styles.xml, and the base application theme is the one referenced in AndroidManifest.xml.Hoenack
FYI Material theme required the name to be android:buttonBarNegativeButtonStyleChilly
import androidx.appcompat.app.AlertDialogBurrus
Unlike the upper-most comment, I had to use buttonBarNegativeButtonStyle to make it work with a parent style of Theme.MaterialComponents.Light.Dialog.Taffeta
My app uses the material night day theme but I'm using a third party SDK that uses AlertDialog, not appcompat or material, just the standard AlertDialog. How can I change the colors on that one? I made a post to share my issue #77581429Coating
P
243

You can try to create the AlertDialog object first, and then use it to set up to change the color of the button and then show it. (Note that on builder object instead of calling show() we call create() to get the AlertDialog object:

//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()

The reason you have to do it on onShow() and cannot just get that button after you create your dialog is that the button would not have been created yet.

I changed AlertDialog.BUTTON_POSITIVE to AlertDialog.BUTTON_NEGATIVE to reflect the change in your question. Although it is odd that "OK" button would be a negative button. Usually it is the positive button.

Powell answered 15/1, 2015 at 14:40 Comment(4)
Thanks for you answer, but I dont have that method in AlertDialog. See my updated post.Cablet
That method is in AlertDialog class, not Builder class. So instead of calling Builder.show() you can Builder.create(), which returns the AlertDialog class. You then set up the listener and then call show() on the AlertDialog objectPowell
But there must be another way to do this. Seems like it's a color from the theme, can we change it through the theme/style?Imalda
This is perfect. Just tried in Xamarin.Android and it works perfeclty. Thank you very much.Pice
C
132

The color of the buttons and other text can also be changed via theme:

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>

The result:

Dialog Date picker

Cesaro answered 20/7, 2015 at 10:54 Comment(10)
Currently I don't know a way to change the checkbox color or button color only. The accent color changes them both.Cesaro
I liked this approach, but I feel like the answer at https://mcmap.net/q/112884/-material-design-not-styling-alert-dialogs is a slightly cleaner way to do it.Operant
This is correct approach, I hate doing some tricks just to make it work.Gonocyte
To get this to work in my project, I had to remove the android: part from android:alertDialogTheme and from android:colorAccent.Broddie
Having the android: prefix on the values depends on where do you put styles.xml, in values or in values-vXXCesaro
To make this work with AppCompat and a simple values folder, simply follow the changes suggested by @BroddieCognize
But this will change the theme of all the dialogs throughout the application isnt it ?Charley
what about pre lollipop devices ? how to achieve this with all the devices ?Past
accent is has minimum api of 21 and this creates an extra space on top of the title.. Not good to change style if you aren't going to override other attributes.According
Strangely enough in my case it was not colorPrimary or colorAccent, but colorOnPrimary (and I didn't change the color anywhere in my code). I guess just another Android version difference. In case someone tries it all here and nothing works, you may need to give colorOnPrimary a chance.Haematopoiesis
S
122

The simpliest solution is:

dialog.show(); //Only after .show() was called
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(neededColor);
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(neededColor);
Shulamith answered 1/5, 2015 at 9:50 Comment(3)
Those fields should not be referenced from the non-static variable, should be AlertDialog.BUTTON_NEGATIVE etc.Velvetvelveteen
This was the best and simplest way to do this. Note that I did not use the "create" rather grabbed the dialog after the show(). Like AlertDialog dialog = builder.show();Monocyclic
While this solution might work, logically it is flawed. What happen here is you first show the dialog, and then you change its appearance. Depends on the underlying implementation (which could be changed over time) and the performance of the device, you could theoretically see a "flicker" where user see a dialog shows up and then quickly change its appearance.Powell
F
56

There are two ways to change the dialog button color.

Basic Way

If you just want to change in an activity, write the below two lines after alertDialog.show();

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

Recommended

I'll recommend adding a theme for AlertDialog in styles.xml so you don't have to write the same code again and again in each activity/dialog call. You can just create a style and apply that theme on the dialog box. So whenever you want to change the color of AlertDialog box, just change color in styles.xml and all the dialog boxes will be updated in the whole application.

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

And apply the theme in AlertDialog.Builder

AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.AlertDialogTheme);
Felipafelipe answered 6/4, 2018 at 11:0 Comment(2)
This answer is the most clean while still being correct.Drivel
Worked! Awesome...Rheology
F
18
  1. In your app's theme/style, add the following lines:

    <item name="android:buttonBarNegativeButtonStyle">@style/NegativeButtonStyle</item>
    <item name="android:buttonBarPositiveButtonStyle">@style/PositiveButtonStyle</item>
    <item name="android:buttonBarNeutralButtonStyle">@style/NeutralButtonStyle</item>
    
  2. Then add the following styles:

    <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>
    

Using this method makes it unneccessary to set the theme in the AlertDialog builder.

Felafel answered 10/3, 2020 at 4:40 Comment(1)
What theme did you apply this to?Begonia
A
13

If you want to change buttons text color (positive, negative, neutral) just add to your custom dialog style:

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

So, your dialog style must looks like this:

<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>
Aframe answered 29/9, 2016 at 17:13 Comment(0)
H
11

Kotlin 2020: Very simple method

After dialog.show() use:

dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(ContextCompat.getColor(requireContext(), R.color.yourColor))
Haplography answered 5/11, 2020 at 11:50 Comment(0)
L
7

Here is how you do it: Simple way

// 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();
Linders answered 23/4, 2020 at 15:30 Comment(0)
G
7

We can create extension function and call the extension function after dialog.show() to customise Alert Dialog button colors.

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))
}

Usage:

dialog.show()
dialog.makeButtonTextBlue()
Gant answered 2/8, 2021 at 5:57 Comment(0)
A
6
<style name="AlertDialogCustom" parent="Theme.AppCompat.Light.Dialog.Alert">
    <item name="android:colorPrimary">#00397F</item>
    <item name="android:textColorPrimary">#22397F</item>
    <item name="android:colorAccent">#00397F</item>
    <item name="colorPrimaryDark">#22397F</item>
</style>

The color of the buttons and other text can also be changed using appcompat :

Arthromere answered 2/2, 2016 at 5:41 Comment(1)
Theme.AppCompat.Light.Dialog.Alert works nicely to change button color to white.Islam
L
5

Using styles.xml (value)

Very Easy solution , change colorPrimary as your choice and it will change color of button text of alert box.

<style name="MyAlertDialogStyle" parent="android:Theme.Material.Dialog.Alert">


        <!-- Used for the buttons -->
        <item name="colorAccent">@android:color/white</item>
        <!-- Used for the title and text -->
        <item name="android:textColorPrimary">@color/black</item>

        <!-- Used for the background -->
        <item name="android:background">#ffffff</item>
        <item name="android:colorPrimary">@color/white</item>
        <item name="android:colorAccent">@color/white</item>
        <item name="android:windowEnterAnimation">@anim/bottom_left_enter</item>
    </style>

Alternative (Using Java)

 @SuppressLint("ResourceAsColor")
            public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {

                AlertDialog dialog = new AlertDialog.Builder(view.getContext(), R.style.MyAlertDialogStyle)

                        .setTitle("Royal Frolics")
                        .setIcon(R.mipmap.ic_launcher)
                        .setMessage(message)
                        .setPositiveButton("OK", (dialog1, which) -> {
                            //do nothing
                            result.confirm();
                        }).create();

                Objects.requireNonNull(dialog.getWindow()).getAttributes().windowAnimations = R.style.MyAlertDialogStyle;
                dialog.show();
                
                dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(R.color.white);
                return true;

            }
Lengthwise answered 24/12, 2020 at 20:59 Comment(0)
R
4

Just as a side note:

The colors of the buttons (and the whole style) also depend on the current theme which can be rather different when you use either

android.app.AlertDialog.Builder builder = new AlertDialog.Builder()

or

android.support.v7.app.AlertDialog.Builder builder = new AlertDialog.Builder()

(Better to use the second one)

Resumption answered 17/11, 2016 at 14:34 Comment(0)
I
2

This is a custom theme to change textColor of buttons on AlertDialog. It works on my device - SamsungA70 - android 11

<style name="AlertDialogCustom" parent="Theme.AppCompat.Light.Dialog.Alert">
    <!--Support for other devices, I think so-->
        <item name="android:textColor">@color/yourcolor</item>
        <item name="colorButtonNormal">@color/yourcolor</item>
        <item name="colorAccent">@color/yourcolor</item>
    <!--only this code works on my device-->
        <item name="buttonBarButtonStyle">@style/MyButtonStyle</item>
    </style>

    <!--only this code works on my device-->
    <style name="MyButtonStyle" parent="Widget.AppCompat.Button.Borderless">
        <item name="android:textColor">@color/yourcolor</item>
    </style>
Identical answered 20/1, 2022 at 15:47 Comment(0)
P
1

For me it was different, I used a button theme

<style name="ButtonLight_pink" parent="android:Widget.Button">
    <item name="android:background">@drawable/light_pink_btn_default_holo_light</item>
    <item name="android:minHeight">48dip</item>
    <item name="android:minWidth">64dip</item>
    <item name="android:textColor">@color/tab_background_light_pink</item>
</style>

and because android:textColor was white there… I didn't see any button text (Dialog buttons are basically buttons too). There we go, changed it, fixed it.

Potpourri answered 20/4, 2017 at 20:56 Comment(0)
E
1

Here's a Kotlin version of the accepted answer from @trungdinhtrong:

val alert = builder.create()
if (button1Text == "Delete") {
    alert.setOnShowListener { dialog ->
        alert.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(Color.RED);
    }
}

BTW, it seems like Android's idea of "positive" and "negative" buttons isn't compatible with the idea of "safe" and "destructive" buttons. In a dialog with Cancel and Delete buttons, I think Android would consider Delete the positive button because it performs an action, but I would consider it a destructive button because it leads to data loss. So instead of using the styles file to set positive and negative button colors, I'm using this code to make the Delete button red even though it's the "positive" button.

Eccles answered 27/10, 2022 at 20:56 Comment(1)
I have tried several solutions but none of them worked except this one.Hakenkreuz
G
0

Fast and easy method: change the colorAccent color in res/values/colors.xml, the color is expressed in hexadecimal, for example #010613 is black. Bye bye

Gargantuan answered 14/1, 2022 at 13:30 Comment(0)
M
0

Looked a lot at styling again while learning a lot. One critical thing to know is that code is a higher order than styling. The styling just wasn't working for the buttons so I thank Ramakrishna Joshi for his answer in this post. I added to it to show in both day and night themes:

private fun AlertDialog.dlgTextColor() {
    val currentNightMode = (resources.configuration.uiMode
            and Configuration.UI_MODE_NIGHT_MASK)
    when (currentNightMode) {
        Configuration.UI_MODE_NIGHT_YES -> {
            this.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(context, R.color.yellow_accent))
            this.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(ContextCompat.getColor(context, R.color.yellow_accent))
        }
        Configuration.UI_MODE_NIGHT_NO -> {
            this.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(ContextCompat.getColor(context, R.color.blue_accent))
            this.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(ContextCompat.getColor(context, R.color.blue_accent))
        }
    }
}

and the call to it is:

.dlgTextColor()

And the call to the method does follow .show in the dialog builder.

Monstrous answered 18/6, 2022 at 20:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.