如何获得TextView的背景颜色?如何获取TextView的背景颜色?
当我按下TextView时,我想根据使用中的背景颜色更改背景颜色。
TextView中没有一个方法,如:
getBackgroundResource()
编辑: 我宁愿让背景色的渣油。
如何获得TextView的背景颜色?如何获取TextView的背景颜色?
当我按下TextView时,我想根据使用中的背景颜色更改背景颜色。
TextView中没有一个方法,如:
getBackgroundResource()
编辑: 我宁愿让背景色的渣油。
答:
我们不能使用consts像color.red或color.white。
我们需要弄清楚它的
int intID = (ColorDrawable) holder.tvChoose.getBackground().getColor();
如何代表它和我们有颜色的假身份证
ColorDrawable.getColor()
将只与上述11 API级别上工作,所以你可以使用此代码从开始就支持它。 我使用以下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;
}
如果您正在使用AppCompat
使用这样的:
ViewCompat.getBackgroundTintList(textView).getDefaultColor();
旁注:要小心,如果你投以ColorDrawable
,因为它可以抛出一个ClassCastException: android.graphics.drawable.RippleDrawable cannot be cast to android.graphics.drawable.ColorDrawable
。
或者我通过互联网寻找一点点,但它似乎没有办法从xml定义的颜色得到这样的id。可能你应该改变你的应用程序并以编程方式管理背景颜色,也许在onClick事件中保留一些颜色变化。 – Rob013