如何仅使用API 9获取textview的背景颜色?
我基本上想要这样做但只使用API 9
int intID = (ColorDrawable) textView.getBackground().getColor();
答案 0 :(得分:5)
试试这个......
public static int getBackgroundColor(TextView textView) {
ColorDrawable drawable = (ColorDrawable) textView.getBackground();
if (Build.VERSION.SDK_INT >= 11) {
return drawable.getColor();
}
try {
Field field = drawable.getClass().getDeclaredField("mState");
field.setAccessible(true);
Object object = field.get(drawable);
field = object.getClass().getDeclaredField("mUseColor");
field.setAccessible(true);
return field.getInt(object);
} catch (Exception e) {
// TODO: handle exception
}
return 0;
}
答案 1 :(得分:3)
很棒的答案!我只是想补充说私有字段mState
有两个颜色字段:
mUseColor
mBaseColor
对于获取上述代码的颜色很棒,但如果您想要设置颜色,则必须将其设置为两个字段,因为{{{ 1}}实例:
StateListDrawable
希望这有用! :)