get background color from textview without using C

2019-02-24 17:30发布

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();

2条回答
叼着烟拽天下
2楼-- · 2019-02-24 18:05

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

查看更多
迷人小祖宗
3楼-- · 2019-02-24 18:15

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;
}
查看更多
登录 后发表回答