我该如何获取TextView的背景颜色?
当我按下TextView时,我想根据当前使用的背景颜色来更改背景颜色。
TextView没有像这样的方法:
getBackgroundResource()
编辑: 我更喜欢获取背景颜色的resId。
如果您想获取背景色的颜色代码,请尝试以下方法:
if (textView.getBackground() instanceof ColorDrawable) {
ColorDrawable cd = (ColorDrawable) textView.getBackground();
int colorCode = cd.getColor();
}
在Kotlin中:
val cd = view.background as ColorDrawable
val colorCode = cd.color
AppCompat
,请使用以下内容:ViewCompat.getBackgroundTintList(textView).getDefaultColor();
注意:如果你将其转换为ColorDrawable
,请小心,因为它可能会抛出一个ClassCastException:android.graphics.drawable.RippleDrawable cannot be cast to android.graphics.drawable.ColorDrawable
异常。
ColorDrawable.getColor()
只能在 API 级别高于 11 的系统上工作,因此您可以使用此代码从一开始就支持它。
我正在使用低于 API 级别 11 的反射。
public static int getBackgroundColor(TextView textView) {
Drawable drawable = textView.getBackground();
if (drawable instanceof ColorDrawable) {
ColorDrawable colorDrawable = (ColorDrawable) drawable;
if (Build.VERSION.SDK_INT >= 11) {
return colorDrawable.getColor();
}
try {
Field field = colorDrawable.getClass().getDeclaredField("mState");
field.setAccessible(true);
Object object = field.get(colorDrawable);
field = object.getClass().getDeclaredField("mUseColor");
field.setAccessible(true);
return field.getInt(object);
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return 0;
}
答案:
我们不能像 color.red 或 color.white 那样使用常量。
我们需要弄清楚如何
int intID = (ColorDrawable) holder.tvChoose.getBackground().getColor();
表示它,我们有颜色的假身份证
R.attr.background
,它对应于您的主题或样式中的<item name="android:background">
。您可以从主题中获取颜色值,并将其与TextView的颜色进行比较,以查看它是否匹配。 - jpaugh