Get the background color of a button in android Get the background color of a button in android android 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");}


private Bitmap mBitmap;private Canvas mCanvas;private Rect mBounds;public void initIfNeeded() {  if(mBitmap == null) {    mBitmap = Bitmap.createBitmap(1,1, Bitmap.Config.ARGB_8888);    mCanvas = new Canvas(mBitmap);    mBounds = new Rect();  }}public int getBackgroundColor(View view) {  // The actual color, not the id.  int color = Color.BLACK;  if(view.getBackground() instanceof ColorDrawable) {    if(Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB) {      initIfNeeded();      // If the ColorDrawable makes use of its bounds in the draw method,      // we may not be able to get the color we want. This is not the usual      // case before Ice Cream Sandwich (4.0.1 r1).      // Yet, we change the bounds temporarily, just to be sure that we are      // successful.      ColorDrawable colorDrawable = (ColorDrawable)view.getBackground();      mBounds.set(colorDrawable.getBounds()); // Save the original bounds.      colorDrawable.setBounds(0, 0, 1, 1); // Change the bounds.      colorDrawable.draw(mCanvas);      color = mBitmap.getPixel(0, 0);      colorDrawable.setBounds(mBounds); // Restore the original bounds.    }    else {      color = ((ColorDrawable)view.getBackground()).getColor();    }  }  return color;}


You can also try something like set the color value as the tag like

android:tag="#ff0000"

And access it from the code

String colorCode = (String)btn.getTag();