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
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
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);
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();
}
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;
}