如何获取按钮的背景颜色

时间:2016-04-19 19:45:29

标签: android

我有一个ImageButton,它的背景是一种颜色

 android:src="@color/c105"

如何以编程方式获取该Color?

我想把它当作Color而不是Drawable

3 个答案:

答案 0 :(得分:1)

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

应该这样做

您可以通过在代码中引用它来设置图像按钮上的颜色,如下所示:

(ImageView) findViewById(R.id.your_image_view).setBackgroundColor(getResources().getColor(R.color.c105);

答案 1 :(得分:0)

如果您知道视图的背景是一种颜色,您可以检索背景drawable,将其转换为ColorDrawable并读取其颜色值:

int color = 0;
Drawable background = imageButton.getBackground();
if (background instanceof ColorDrawable) {
    color = ((ColorDrawable)background).getColor();
}

答案 2 :(得分:0)

请使用此:

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