Android 如何获取按钮的背景色
我有一个ImageButton,它的背景是一种颜色Android 如何获取按钮的背景色,android,Android,我有一个ImageButton,它的背景是一种颜色 android:src="@color/c105" 如何通过编程获得该颜色 我想将其作为颜色而不是可绘制的如果您知道视图的背景是一种颜色,您可以检索可绘制的背景,将其转换为可绘制的并读取其颜色值: int color = 0; Drawable background = imageButton.getBackground(); if (background instanceof ColorDrawable) { color = ((
android:src="@color/c105"
如何通过编程获得该颜色
我想将其作为颜色而不是可绘制的如果您知道视图的背景是一种颜色,您可以检索可绘制的背景,将其转换为可绘制的并读取其颜色值:
int color = 0;
Drawable background = imageButton.getBackground();
if (background instanceof ColorDrawable) {
color = ((ColorDrawable)background).getColor();
}
应该这样做
您可以通过在代码中引用图像按钮来设置其颜色,如下所示:
(ImageView) findViewById(R.id.your_image_view).setBackgroundColor(getResources().getColor(R.color.c105);
请使用这个:
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;
}
?如果它不是可着色的
怎么办?如果我在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;
}