2

I have an ImageButton and its Background is a color

 android:src="@color/c105"

how can I get that Color programmatically ?

I want to get it as Color not as Drawable

maysara
  • 5,873
  • 2
  • 23
  • 34

3 Answers3

1
getResources().getColor(r.color.c105);

should do it

You could set the color on the image button by having a reference to it in your code like this:

(ImageView) findViewById(R.id.your_image_view).setBackgroundColor(getResources().getColor(R.color.c105);
kimchibooty
  • 339
  • 1
  • 11
0

If you know that the background of your View is a color, you can retrieve the background drawable, cast it to a ColorDrawable and read its color value:

int color = 0;
Drawable background = imageButton.getBackground();
if (background instanceof ColorDrawable) {
    color = ((ColorDrawable)background).getColor();
}
Floern
  • 33,559
  • 24
  • 104
  • 119
  • 1
    what if it is not a `ColorDrawable`? If I add a button in Android Studio without changing its default colour, `imageButton.getBackground();` returns a `RippleDrawable` and `RippleDrawable` has no `.getColor()` method. However if I manually choose a colour for the button background, then that same line would return a `ColorDrawable`. How can I handle the `RippleDrawable` case? – rockhammer Oct 22 '16 at 22:09
0

Please use this:

private int getButtonBackgroundColor(Button button){
            int buttonColor = 0;

            if (button.getBackground() instanceof ColorDrawable) {
                ColorDrawable cd = (ColorDrawable) button.getBackground();
                buttonColor = cd.getColor();
            }

            if (button.getBackground() instanceof RippleDrawable) {
                RippleDrawable rippleDrawable = (RippleDrawable) button.getBackground();
                Drawable.ConstantState state = rippleDrawable.getConstantState();
                try {
                    Field colorField = state.getClass().getDeclaredField("mColor");
                    colorField.setAccessible(true);
                    ColorStateList colorStateList = (ColorStateList) colorField.get(state);
                    buttonColor = colorStateList.getDefaultColor();
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
            return buttonColor;
        }
vietlh
  • 39
  • 3