在不使用ColorDrawable(API 11)的情况下从textview获取背景颜色

时间:2014-02-15 09:48:42

标签: android colors background textview

如何仅使用API​​ 9获取textview的背景颜色?

我基本上想要这样做但只使用API​​ 9

int intID = (ColorDrawable) textView.getBackground().getColor();

2 个答案:

答案 0 :(得分:5)

试试这个......

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;
}

答案 1 :(得分:3)

很棒的答案!我只是想补充说私有字段mState有两个颜色字段:

  • mUseColor
  • mBaseColor

对于获取上述代码的颜色很棒,但如果您想要设置颜色,则必须将其设置为两个字段,因为{{{ 1}}实例:

StateListDrawable

希望这有用! :)