Get background color from text field without using ColorDrawable (API 11)

How can I get the background color of a textview using only API 9?

I just want to do this, but only using API 9

int intID = (ColorDrawable) textView.getBackground().getColor();
+4
source share
2 answers

try it...

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;
}
+5
source

Great answer! I just wanted to add that the private field mStatehas two color fields:

  • mUseColor
  • mBaseColor

To get the color, the code above, but if you want to set the color, you must set it in both fields due to problems in the StateListDrawableinstances:

    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! :)

+3

Source: https://habr.com/ru/post/1527075/


All Articles