4
如何獲取僅使用API 9的textview的背景顏色?從textview中獲取背景顏色而不使用ColorDrawable(API 11)
我basicly想這樣做,但只能使用API 9
int intID = (ColorDrawable) textView.getBackground().getColor();
如何獲取僅使用API 9的textview的背景顏色?從textview中獲取背景顏色而不使用ColorDrawable(API 11)
我basicly想這樣做,但只能使用API 9
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!");
}
}
希望這有幫助! :)
謝謝你的作品。我必須在方法中添加@SuppressLint(「NewApi」),現在只使用API 9 –
在API> 21上失敗 – EmmanuelMess