Get the Background Color of a Button in Android

Get the background color of a button in android

Unfortunately I don't know how to retrieve the actual color.

It's easy to get this as a Drawable

Button button = (Button) findViewById(R.id.my_button);
Drawable buttonBackground = button.getBackground();

If you know this is a color then you can try

ColorDrawable buttonColor = (ColorDrawable) button.getBackground();

And if you're on Android 3.0+ you can get out the resource id of the color.

int colorId = buttonColor.getColor();

And compare this to your assigned colors, ie.

if (colorID == R.color.green) {
log("color is green");
}

How do you get the background color of a button?

Since you are using a MaterialComponents theme your Button is replaced at runtime by a MaterialButton.

Use the setBackgroundTintList instead of the setBackgroundColor and use getBackgroundTintList() to retrieve the ColorStateList.

Something like:

    MaterialButton button = findViewById(R.id.button);
button.setBackgroundTintList(ColorStateList.valueOf(ContextCompat.getColor(this, R.color.red600)));
ColorStateList colorStateList = button.getBackgroundTintList();

int defaultColor = colorStateList.getColorForState(
new int[] { android.R.attr.state_enabled},0);

how to get background color of button on android?

Here ya go ....

 Button myButton = (Button) findViewById(R.id.takePicture);

myButton.setBackgroundDrawable(new PaintDrawable(Color.YELLOW));

PaintDrawable drawable = (PaintDrawable) myButton.getBackground();

int color = drawable.getPaint().getColor();

Android button background color

If you want to keep the general styling (rounded corners etc.) and just change the background color then I use the backgroundTint property

android:backgroundTint="@android:color/holo_green_light"


Related Topics



Leave a reply



Submit