【发布时间】:2016-08-12 04:49:51
【问题描述】:
我有一个 ImageButton,它的背景是一种颜色
android:src="@color/c105"
如何以编程方式获得该颜色?
我想把它作为 Color 而不是 Drawable
【问题讨论】:
标签: android
我有一个 ImageButton,它的背景是一种颜色
android:src="@color/c105"
如何以编程方式获得该颜色?
我想把它作为 Color 而不是 Drawable
【问题讨论】:
标签: android
getResources().getColor(r.color.c105);
应该这样做
您可以通过在代码中引用它来设置图像按钮的颜色,如下所示:
(ImageView) findViewById(R.id.your_image_view).setBackgroundColor(getResources().getColor(R.color.c105);
【讨论】:
如果您知道 View 的背景是一种颜色,则可以检索背景可绘制对象,将其转换为 ColorDrawable 并读取其颜色值:
int color = 0;
Drawable background = imageButton.getBackground();
if (background instanceof ColorDrawable) {
color = ((ColorDrawable)background).getColor();
}
【讨论】:
ColorDrawable怎么办?如果我在 Android Studio 中添加一个按钮而不更改其默认颜色,imageButton.getBackground(); 将返回一个RippleDrawable 并且RippleDrawable 没有.getColor() 方法。但是,如果我手动选择按钮背景的颜色,那么同一行将返回 ColorDrawable。我该如何处理RippleDrawable 案子?
请使用这个:
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;
}
【讨论】: