android set button background programmatically
Asked Answered
D

11

56

I would like to know how to set the button color programatically? I have coded the following but fails:

Button11.setBackgroundColor(R.color.red);

Thanks!!

Danaedanaher answered 12/12, 2012 at 14:59 Comment(6)
what effect are you trying to get? A plain red rectangle with no additional effects? If not you're going to need some sort of drawable to achieve what your after, either a png (9patch) or something defined in xml. The system has no built in way to make a button that looks like a normal button except a different color. You'll have to provide your own resource unless you are looking for just a plain single colored rectangle.Geranium
actually what i am doing is that out of a table of 12 buttons, the program would randomly select 6 of them to fill in defined text. I would like these 6 buttons to change into another different color. In this regards, it cannot be done in the xml part but just be programmatically. I have already defined some xml (first unselected is plain green round color, if selected i wish it become plain red round color) If in this way, can it be done?Danaedanaher
Right but you either need to have a red button image like a 9patch png, or you'll need to define a red button shape in xml. If you simply change the background color to red you are going to end up with a plain red rectangle not something that looks like a normal button.Geranium
yes u are correct i have modified and it reli gives out a plain red rectangle that even cannot pressed!! I have already separately defined red_button_xml, how could that be incorporated to the Activity? Thanks a lot!Danaedanaher
you'll want Button.setBackgroundResource() instead of setBackgroundColor()Geranium
android:backgroundTint="@color/button_background_color" geeksforgeeks.org/…Cobb
G
109

R.color.red is an ID (which is also an int), but is not a color.

Use one of the following instead:

// If you're in an activity:
Button11.setBackgroundColor(getResources().getColor(R.color.red));
// OR, if you're not: 
Button11.setBackgroundColor(Button11.getContext().getResources().getColor(R.color.red));

Or, alternatively:

Button11.setBackgroundColor(Color.RED); // From android.graphics.Color

Or, for more pro skills:

Button11.setBackgroundColor(0xFFFF0000); // 0xAARRGGBB
Gemeinschaft answered 12/12, 2012 at 15:2 Comment(3)
How do i set different colors for more than one button which is programmatically created ?Below
But it erases all styles, like borders or rounded corners. So it sets color for button area in fact, not button color like OP requested.Medium
Consider that getColor() is deprecated now. Use ContextCompat https://mcmap.net/q/50140/-getcolor-int-id-deprecated-on-android-6-0-marshmallow-api-23Utimer
B
49

Old thread, but learned something new, hope this might help someone.

If you want to change the background color but retain other styles, then below might help.

button.getBackground().setColorFilter(ContextCompat.getColor(this, R.color.colorAccent), PorterDuff.Mode.MULTIPLY);
Bomb answered 14/12, 2015 at 6:17 Comment(4)
setColorFilter only sets a tint to the existing background. It doesn't set a new background colour.Sunnysunproof
If you are using material style raised button, this is what will work. Not Button.setBackgroundColor().Darees
It's 2017 now and it is still sooo ugly to write this whole bunch of boilerplate in order to set the color from resource...Aftercare
Why use PorterDuff.Mode.MULTIPLY instead of PorterDuff.Mode.SRC? Won't the former just mix in with the existing color?Lindsley
A
9

The answer you're looking for in 2020 and beyond:

  • setColorFilter(color, mode) is deprecated since API 29 (as discussed here)
  • button.setBackgroundColor(color) messes with the button style

Now the proper way to set a buttons color is using BlendModeColorFilter() (see documentation).

Usage:

btn.background.colorFilter = BlendModeColorFilter(color, BlendMode.MULTIPLY)

If you work with older APIs too:

fun setButtonColor(btn: Button, color: Int) {
    if (Build.VERSION.SDK_INT >= 29)
        btn.background.colorFilter = BlendModeColorFilter(color, BlendMode.MULTIPLY)
    else
        btn.background.setColorFilter(color, PorterDuff.Mode.MULTIPLY)
}

Please vote to help others finding this answer - it took me quite a while figuring this out ^^

Amative answered 23/5, 2020 at 23:46 Comment(3)
Your method will work IF AND ONLY IF the original color of the button is white. This is due to the fact that MULTIPLY method takes into account the source color.Passbook
This works, but not if a button is styled in the your xml with style=?android:attr/borderlessButtonStyle.Condemnatory
this is not working for me! It still pulls the default color set on styles.xmlIchabod
L
6

You can set your desired color to the button programmatically like:

Button11.setBackgroundColor(Android.Graphics.Color.parseColor("#738b28"));

Also you can give the text color for a button like:

Button11.setTextColor(Android.Graphics.Color.parseColor("#FFFFFF"));
Librarianship answered 26/10, 2018 at 5:33 Comment(1)
btn.setBackgroundColor(Color.parseColor("#97a0ad")); also worksLuculent
P
3

I have found that Android Studio gives me a warning that getColor() is deprecated when trying to do this:

Button11.setBackgroundColor(getResources().getColor(R.color.red))

So I found doing the method below to be the simple, up-to-date solution:

Button11.setBackgroundColor(ContextCompat.getColor(context, R.color.red))

You want to avoid hard-coding in the color argument, as it is considered bad code style.

Edit: After using setBackgroundColor() with my own button, I saw that the internal button padding expanded. I couldn't find any way of changing it back to having both height and width set to "wrap_content". Maybe its a bug.

Source: https://mcmap.net/q/73283/-getresources-getcolor-is-deprecated-duplicate

Petepetechia answered 10/6, 2018 at 4:6 Comment(0)
R
1

For not changing the size of button on setting the background color:

button.getBackground().setColorFilter(button.getContext().getResources().getColor(R.color.colorAccent), PorterDuff.Mode.MULTIPLY);

this didn't change the size of the button and works with the old android versions too.

Rowdyism answered 12/9, 2018 at 18:22 Comment(0)
S
1

Using setBackgroundColor() affects the style. So, declare a new style of the same properties with respect to the previous button, with a a different color.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@color/green"/>
<corners android:radius="10dp"/>
</shape>

Now, use OnClick method.

location.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            location.setBackgroundResource(R.drawable.green);

        }
    });

this changes the button but looks similar to changing the background.

Solecism answered 31/5, 2020 at 12:6 Comment(0)
G
1

Further from @finnmglas, the Java answer as of 2021 is:

    if (Build.VERSION.SDK_INT >= 29)
        btn.getBackground().setColorFilter(new BlendModeColorFilter(color, BlendMode.MULTIPLY));
    else
        btn.getBackground().setColorFilter(color, PorterDuff.Mode.MULTIPLY);
Goran answered 18/1, 2021 at 11:38 Comment(0)
B
0
button.setBackgroundColor(getResources().getColor(R.color.red);

Sets the background color for this view. Parameters: color the color of the background

R.color.red is a reference generated at the compilation in gen.

Baugher answered 12/12, 2012 at 15:5 Comment(0)
R
0

You can use the below code for the button color without getting effected the style if used any

 yourbtnid.background.setColorFilter(ContextCompat.getColor(context, yourcolor), PorterDuff.Mode.SRC)
Resignation answered 8/3, 2021 at 4:46 Comment(0)
D
0

I've tried all of the above answers setColorFilter, setBackgroundColor,colorFilter and so on, but nothing actually worked, all I was getting was a default color.

What worked for me was to use the backgroundTintList like this:

myButton.backgroundTintList = ContextCompat.getColorStateList(this, R.color.red)

Or

myButton.backgroundTintList = ColorStateList.valueOf(Color.RED)
Dekaliter answered 23/5, 2023 at 7:17 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.