Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get background color from textview without using ColorDrawable (API 11)

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();
like image 449
Nicolas Ørskov Skaanild Avatar asked Feb 13 '23 19:02

Nicolas Ørskov Skaanild


2 Answers

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;
}
like image 55
Gopal Gopi Avatar answered Feb 16 '23 07:02

Gopal Gopi


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

like image 33
Kiril Aleksandrov Avatar answered Feb 16 '23 07:02

Kiril Aleksandrov