Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/214.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Android 在不使用ColorDrawable的情况下从textview获取背景色(API 11)_Android_Colors_Background_Textview - Fatal编程技术网

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

Android 在不使用ColorDrawable的情况下从textview获取背景色(API 11),android,colors,background,textview,Android,Colors,Background,Textview,如何仅使用API 9获取textview的背景颜色 我基本上想这样做,但只使用API 9 int intID = (ColorDrawable) textView.getBackground().getColor(); 试试这个 public static int getBackgroundColor(TextView textView) { ColorDrawable drawable = (ColorDrawable) textView.getBackground(); i

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

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

int intID = (ColorDrawable) textView.getBackground().getColor();
试试这个

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

回答得好!我只想补充一点,私有字段
mState
有两个颜色字段:

  • mUseColor
  • mBaseColor
对于获取颜色,上面的代码很棒,但是如果您想设置颜色,则必须将其设置为两个字段,因为
StateListDrawable
实例中存在问题:

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

希望这有帮助!:)

谢谢,这很有效。我不得不在methode上添加@SuppressLint(“NewApi”),因为在API>21时,im仅使用API 9失败