198

I'm trying to set the background color of a View (in this case a Button).

I use this code:

// set the background to green
v.setBackgroundColor(0x0000FF00 );
v.invalidate();

It causes the Button to disappear from the screen. What am I doing wrong, and what is the correct way to change the background color on any View?

Thanks.

Jeremy Logan
  • 47,151
  • 38
  • 123
  • 143
Peter vdL
  • 4,953
  • 10
  • 40
  • 60
  • 1
    That looks correct. In fact, I don't think you need to call invalidate(). When you say the button disappears, do you mean that literally or do you mean the button had text or an image on it that disappears? – RickNotFred Feb 01 '10 at 00:22

22 Answers22

300

You made your button transparent. The first byte is the alpha.

Try v.setBackgroundColor(0xFF00FF00);

Jorgesys
  • 124,308
  • 23
  • 334
  • 268
rainhut
  • 3,164
  • 1
  • 18
  • 4
  • 2
    EddieB's answer below is much better as this removes any borders etc. such as an EditText's underlining – Molten Ice Jul 27 '14 at 11:19
  • @aroth is better Color.Green ? If I want color complext with argb ? ... your answer is deprecated –  Aug 03 '15 at 16:05
  • 2
    @delive - Come again? [Color.GREEN](http://developer.android.com/reference/android/graphics/Color.html#GREEN) is _not_ deprecated, and includes the alpha byte. It's value is `0xff00ff00`, _exactly_ the same as what's suggested in the answer, except it also has the benefit of being _human-readable_. Most developers would prefer a human-readable solution. – aroth Aug 03 '15 at 16:12
  • What do you write between the brackets when you want to refer to a color in your colors.xml? – Steven Sep 19 '21 at 08:40
153

When you call setBackgoundColor it overwrites/removes any existing background resource, including any borders, corners, padding, etc. What you want to do is change the color of the existing background resource...

View v;
v.getBackground().setColorFilter(Color.parseColor("#00ff00"), PorterDuff.Mode.DARKEN);

Experiment with PorterDuff.Mode.* for different effects.

Ozair Kafray
  • 13,351
  • 8
  • 59
  • 84
EddieB
  • 4,991
  • 3
  • 23
  • 18
144

Several choices to do this...

Set background to green:

v.setBackgroundColor(0x00FF00);

Set background to green with Alpha:

v.setBackgroundColor(0xFF00FF00);

Set background to green with Color.GREEN constant:

v.setBackgroundColor(Color.GREEN);

Set background to green defining in Colors.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>     
    <color name="myGreen">#00FF00</color> 
    <color name="myGreenWithAlpha">#FF00FF00</color> 
</resources>

and using:

v.setBackgroundResource(R.color.myGreen);

and:

v.setBackgroundResource(R.color.myGreenWithAlpha);

or the longer winded:

v.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.myGreen));

and:

v.setBackgroundColor(ContextCompat.getColor(getContext(), R.color.myGreenWithAlpha));
weston
  • 54,145
  • 21
  • 145
  • 203
Jorgesys
  • 124,308
  • 23
  • 334
  • 268
  • `getResources().getColor(...)` got deprecated http://stackoverflow.com/questions/31842983/getresources-getcolor-is-deprecated – Junior Mayhé Dec 25 '15 at 20:33
  • 5
    There's also: `v.setBackgroundResource(R.color.myGreen);` when using `colors.xml` – grim Mar 25 '16 at 15:45
  • Removed the `invalidate` calls, as you can [see](http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.0_r1/android/view/View.java#View.setBackgroundDrawable%28android.graphics.drawable.Drawable%29) `setBackground...` methods already call that. – weston Feb 27 '17 at 18:08
  • `v.setBackgroundColor(0x00FF00);` is just their code which they say isn't working. I would also expect it to be transparent. – weston Feb 27 '17 at 18:11
40

You can set the hex-color to any resource with:

View.setBackgroundColor(Color.parseColor("#e7eecc"));
Mobiletainment
  • 22,201
  • 9
  • 82
  • 98
Darsh Patel
  • 1,015
  • 9
  • 15
16
// set the background to green
v.setBackgroundColor(0x0000FF00 );
v.invalidate();

The code does not set the button to green. Instead, it makes the button totally invisible.

Explanation: the hex value of the color is wrong. With an Alpha value of zero, the color will be invisible.

The correct hex value is 0xFF00FF00 for full opacity green. Any Alpha value between 00 and FF would cause transparency.

Andrew T.
  • 4,701
  • 8
  • 43
  • 62
malte kosian
  • 161
  • 1
  • 2
13

For setting the first color to be seen on screen, you can also do it in the relevant layout.xml (better design) by adding this property to the relevant View:

android:background="#FF00FF00"
JustinB
  • 311
  • 3
  • 6
12

and what is the correct way to change the background color on any View?

On any View? What you have is correct, though you should drop the invalidate() call.

However, some Views already have backgrounds. A Button, for example, already has a background: the face of the button itself. This background is a StateListDrawable, which you can find in android-2.1/data/res/drawable/btn_default.xml in your Android SDK installation. That, in turn, refers to a bunch of nine-patch bitmap images, available in multiple densities. You would need to clone and modify all of that to accomplish your green goals.

In short, you will be better served finding another UI pattern rather than attempting to change the background of a Button.

CommonsWare
  • 986,068
  • 189
  • 2,389
  • 2,491
  • OK, thanks for the explanation about Button backgrounds. Nine patch bitmaps (http://developer.android.com/reference/android/graphics/NinePatch.html) were new to me. I simply want to change the color of anything on the screen when I press a Button. The Buttons are on a TextView. Trying to change the color of that, leads to console messages "DDM dispatch reg wait timeout... ActivityManager: Can't dispatch DDM chunk 52454151: no handler defined" and a dialog on screen "the app stopped unexpectedly". Guess I need to do more reading on the UI. Any hints welcome. Thanks. – Peter vdL Feb 01 '10 at 15:16
12

try to add:

setBackgroundColor(Color.parseColor("#FF0000"));
Long Rainbow
  • 328
  • 3
  • 10
7

I use at API min 16 , target 23

Button WeekDoneButton = (Button) viewWeeklyTimetable.findViewById(R.id.week_done_button);

WeekDoneButton.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.colorAccent));
Vostro
  • 197
  • 2
  • 3
7

This works for me

v.getBackground().setTint(Color.parseColor("#212121"));

That way only changes the color of the background without change the background itself. This is usefull for example if you have a background with rounded corners.

Martin Olariaga
  • 379
  • 4
  • 4
6
mButton.setBackgroundColor(getResources().getColor(R.color.myColor));
Gianluca Demarinis
  • 1,964
  • 2
  • 15
  • 21
5

You can simple use :

view.setBackgroundColor(Color.parseColor("#FFFFFF"));
daniel kilinskas
  • 3,538
  • 3
  • 16
  • 10
5

You can simple use :

view.setBackgroundColor(Color.rgb(0, 198, 255));
Mahmoud Salah Eldin
  • 1,739
  • 16
  • 21
4

Stating with Android 6 use ContextCompact

        view.setBackgroundColor( ContextCompat.getColor(this, R.color.your_color));
Raluca Lucaci
  • 2,058
  • 3
  • 20
  • 37
4

This question talks about changing the background color of a view. In one of the answers, the person explains how to change the background color during runtime. Obviously you are going to look into how to modify other objects on the screen, but this should give you a good start by at least allowing you to modify the background color of the view on button click.

Community
  • 1
  • 1
jbranchaud
  • 5,909
  • 9
  • 45
  • 70
2

In kotlin you could do it like this:

val backgroundColor = R.color.whatever_color_you_like
view.setBackgroundColor(getColorCompat(backgroundColor))

Where getColorCompat() is an extension function:

/**
 * Extension method to provide simpler access to {@link ContextCompat#getColor(int)}.
 */

 fun Context.getColorCompat(color: Int) = ContextCompat.getColor(this, color)
1
view.setBackgroundColor(R.color.primaryColor);

Adds color to previous color value, so i have a different color.

What works for me is :

view.setBackgroundResource(R.color.primaryColor);
meralon
  • 9
  • 4
1

Let suppose we have a primary color in values=>colors.xml as:

<resources>
    <color name="primary">#FDD835</color>
</resources>

so if we want to use our custom color into setBackgroundColor(@ColorInt int Color) then we just need an annotation @SuppressLint("ResourceAsColor") with constructor/method which will be used as:

    @SuppressLint("ResourceAsColor")
    public _LinearLayout(Context context) {
        super(context);

        // Formatting our layout : )
        super.setBackgroundColor(R.color.primary);

        ....


    }
ForWebTech
  • 140
  • 1
  • 13
0

You must pass an int in the argument.

First Example:

view.setBackgroundColor(-500136)

Second Example:

int colorId = R.color.green;

view.setBackgroundResource(colorId);
Teamothy
  • 2,000
  • 3
  • 16
  • 26
0

This should work fine: v.setBackgroundColor(0xFF00FF00);

slfan
  • 8,950
  • 115
  • 65
  • 78
nishanuw
  • 49
  • 1
  • 11
0

I tried all the above ways. But I havent achieve what i need. Here is my try. If you are using hexcode for color and want to set the color as background of image, then this is the kotlin code.

val bitmap = Bitmap.createBitmap(30, 30, Bitmap.Config.ARGB_8888)
val canvas = Canvas(bitmap)
val colorCode = "#ffffff"
canvas.drawColor(Color.parseColor(colorCode))
mImageViewLogo.setImageBitmap(bitmap)
Shaffz
  • 1
  • 2
0

When calling setBackgroundColor on a view you need to set the alpha value to a non-zero value (e.g. 0xFF), otherwise the color will not show up.

TextView tv = (TextView)findViewById(R.id.myTextview);
int rgb = 0xF05922; // Orange
tv.setBackgroundColor(0xFF000000|rgb); // Use bitwise OR to add alpha to RGB value
Anthony.
  • 643
  • 7
  • 14