Android 在不使用ColorDrawable的情况下从textview获取背景色(API 11)
如何仅使用API 9获取textview的背景颜色 我基本上想这样做,但只使用API 9Android 在不使用ColorDrawable的情况下从textview获取背景色(API 11),android,colors,background,textview,Android,Colors,Background,Textview,如何仅使用API 9获取textview的背景颜色 我基本上想这样做,但只使用API 9 int intID = (ColorDrawable) textView.getBackground().getColor(); 试试这个 public static int getBackgroundColor(TextView textView) { ColorDrawable drawable = (ColorDrawable) textView.getBackground(); i
int intID = (ColorDrawable) textView.getBackground().getColor();
试试这个
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
有两个颜色字段:
mUseColor
mBaseColor
StateListDrawable
实例中存在问题:
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!");
}
}
希望这有帮助!:) 谢谢,这很有效。我不得不在methode上添加@SuppressLint(“NewApi”),因为在API>21时,im仅使用API 9失败