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
Sqlite Android Database Cursor Window Allocation of 2048 Kb Failed
How to Detect Orientation of Android Device
Download Files and Store Them Locally with Phonegap/Jquery Mobile Android and iOS Apps
Opening Android Settings Programmatically
How to Customize Item Background and Item Text Color Inside Navigationview
Programmatically Getting the Gateway and Subnet Mask Details
Android Http Connection Exception
How to Achieve Gapless Audio Looping So Far on Android
Multiple Instances of Widget Only Updating Last Widget
Removing a Fragment from the Back Stack
How to Change Default Images of Checkbox
Programmatically Relaunch/Recreate an Activity
Is an Android Service Guaranteed to Call Ondestroy()
Save Image to Sdcard from Drawable Resource on Android
Android.Content.Context.Getpackagename()' on a Null Object Reference