[android] How to set background color of a View

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.

This question is related to android view colors background set

The answer is


You can simple use :

view.setBackgroundColor(Color.rgb(0, 198, 255));

Stating with Android 6 use ContextCompact

        view.setBackgroundColor( ContextCompat.getColor(this, R.color.your_color));

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


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

        ....


    }

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.


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

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

View.setBackgroundColor(Color.parseColor("#e7eecc"));

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"

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.


You can simple use :

view.setBackgroundColor(Color.parseColor("#FFFFFF"));

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


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)

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

You must pass an int in the argument.

First Example:

view.setBackgroundColor(-500136)

Second Example:

int colorId = R.color.green;

view.setBackgroundResource(colorId);

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)

try to add:

setBackgroundColor(Color.parseColor("#FF0000"));

mButton.setBackgroundColor(getResources().getColor(R.color.myColor));

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

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.


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.


Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to view

Empty brackets '[]' appearing when using .where SwiftUI - How do I change the background color of a View? Drop view if exists Difference between View and ViewGroup in Android How to make a view with rounded corners? How to remove all subviews of a view in Swift? How to get a view table query (code) in SQL Server 2008 Management Studio how to add button click event in android studio How to make CREATE OR REPLACE VIEW work in SQL Server? Android findViewById() in Custom View

Examples related to colors

is it possible to add colors to python output? How do I use hexadecimal color strings in Flutter? How do I change the font color in an html table? How do I print colored output with Python 3? Change bar plot colour in geom_bar with ggplot2 in r How can I color a UIImage in Swift? How to change text color and console color in code::blocks? Android lollipop change navigation bar color How to change status bar color to match app in Lollipop? [Android] How to change color of the back arrow in the new material theme?

Examples related to background

SwiftUI - How do I change the background color of a View? Changing background color of selected item in recyclerview Android Studio Image Asset Launcher Icon Background Color Android: keep Service running when app is killed How to set a background image in Xcode using swift? CSS Background image not loading css transition opacity fade background how to set the background image fit to browser using html background:none vs background:transparent what is the difference? How to scale images to screen size in Pygame

Examples related to set

java, get set methods golang why don't we have a set datastructure Simplest way to merge ES6 Maps/Sets? Swift Set to Array JavaScript Array to Set How to sort a HashSet? Python Set Comprehension How to get first item from a java.util.Set? Getting the difference between two sets Python convert set to string and vice versa