Reputation: 730
I understand that to set a hex colour of a dynamic button, you can write:
button.setBackgroundColor(Color.parseColor("#FFFFFF"));
But how can I get the colour of the button?
I need this as the button changes colour depending on clicks so I want to write and if statement depending on the colour of the button at the time.
After reading other various answers, they haven't worked for me, unfortunately.
I have tried:
Drawable buttonBackground = button.getBackground();
ColorDrawable buttonColour = (ColorDrawable) button.getBackground();
But this will not allow me to make a comparison using hex codes, e.g.
if (buttonColour == "#FFFFFF"){
//do stuff
}
I have also tried to set the colour in values/colors
<color name="notPresent">#FFFFFF</color>
Then in my code:
String buttonColour= button.getResources().getString(R.color.notPresent);
Then made a comparison using an if statement, but this also fails.
Upvotes: 1
Views: 472
Reputation: 2355
Getting the int color not only button but any View
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;
}
Hex Format of (#EE111000)
covert to hex without losing opacity
String hexColorWithOpacity = Integer.toHexString(intColorFromPreviosStep);
Upvotes: 0
Reputation: 2774
Button is a view. You can get solid color of view like this
int color = Color.TRANSPARENT;
Drawable bg = view.getBackground();
if (bg instanceof ColorDrawable)
color = ((ColorDrawable) background).getColor();
Then convert it to color HEX like
String hexColor = String.format("#%06X", (0xFFFFFF & intColor));
Upvotes: 2