API 9 만 사용하여 textview의 배경색을 어떻게 얻을 수 있습니까?ColorDrawable (API 11)을 사용하지 않고 textview에서 배경색 가져 오기
나는 basicly이 작업을 수행 할 수 있지만 API 9
int intID = (ColorDrawable) textView.getBackground().getColor();
API 9 만 사용하여 textview의 배경색을 어떻게 얻을 수 있습니까?ColorDrawable (API 11)을 사용하지 않고 textview에서 배경색 가져 오기
나는 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;
}
멋진 대답을 사용! 를 들어
mUseColor
mBaseColor
위의 코드는 설정하려면 큰하지만 색상을 받고 : 난 그냥 private 필드 mState
는 두 가지 색상 필드를 가지고 추가하고 싶었 색상의 경우 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")를 methode에 추가해야만 API 9를 사용하고 있습니다. –
API> 21에서 실패합니다. – EmmanuelMess