【问题标题】:get background color from textview without using ColorDrawable (API 11)不使用 ColorDrawable (API 11) 从 textview 获取背景颜色
【发布时间】:2017-09-12 21:04:26
【问题描述】:

如何仅使用 API 9 获得文本视图的背景颜色?

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

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

【问题讨论】:

    标签: android colors background textview


    【解决方案1】:

    试试这个...

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

    【讨论】:

    • 谢谢你的作品。我必须在方法上添加 @SuppressLint("NewApi") ,因为我只使用 API 9
    • API 失败 > 21
    【解决方案2】:

    很好的答案!我只是想补充一点,私有字段mState 有两个颜色字段:

    • mUseColor
    • mBaseColor

    对于获取颜色,上面的代码很棒,但是如果你想设置颜色,你必须将它设置到这两个字段中,因为@987654324 中的问题@实例:

        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!");
            }
        }
    

    希望这对您有所帮助! :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-06-11
      • 1970-01-01
      • 2019-05-29
      • 1970-01-01
      相关资源
      最近更新 更多