How can i get the backround color of a textview using only API 9?
I basicly want to do this but only using API 9
int intID = (ColorDrawable) textView.getBackground().getColor();
try this...
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;
}
Great answer! I just wanted to add that the private field mState
has two color fields:
mUseColor
mBaseColor
For getting the color the above code is great but if you want to set the color, you have to set it to the both fields due to problems in StateListDrawable
instances:
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!");
}
}
Hope this was helpful! :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With