【发布时间】:2017-09-12 21:04:26
【问题描述】:
如何仅使用 API 9 获得文本视图的背景颜色?
我基本上想这样做,但只使用 API 9
int intID = (ColorDrawable) textView.getBackground().getColor();
【问题讨论】:
标签: android colors background textview
如何仅使用 API 9 获得文本视图的背景颜色?
我基本上想这样做,但只使用 API 9
int intID = (ColorDrawable) textView.getBackground().getColor();
【问题讨论】:
标签: android colors background textview
试试这个...
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;
}
【讨论】:
很好的答案!我只是想补充一点,私有字段mState 有两个颜色字段:
mUseColormBaseColor 对于获取颜色,上面的代码很棒,但是如果你想设置颜色,你必须将它设置到这两个字段中,因为@987654324 中的问题@实例:
final int color = Color.RED;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
drawable.setColor(color);
} else {
try {
final Field stateField = drawable.getClass().getDeclaredField(
"mState");
stateField.setAccessible(true);
final Object state = stateField.get(drawable);
final Field useColorField = state.getClass().getDeclaredField(
"mUseColor");
useColorField.setAccessible(true);
useColorField.setInt(state, color);
final Field baseColorField = state.getClass().getDeclaredField(
"mBaseColor");
baseColorField.setAccessible(true);
baseColorField.setInt(state, color);
} catch (Exception e) {
Log.e(LOG_TAG, "Cannot set color to the drawable!");
}
}
希望这对您有所帮助! :)
【讨论】: