Android 如何获取TextView的背景色?

Android 如何获取TextView的背景色?,android,textview,Android,Textview,如何获取TextView的背景色 当我按下文本视图时,我想根据正在使用的背景色更改背景色 TextView没有以下方法: getBackgroundResource() 编辑: 我更喜欢获取背景色的残差。如果要获取背景色代码,请尝试以下操作: if (textView.getBackground() instanceof ColorDrawable) { ColorDrawable cd = (ColorDrawable) textView.getBackground(); i

如何获取TextView的背景色

当我按下文本视图时,我想根据正在使用的背景色更改背景色

TextView没有以下方法:

getBackgroundResource()
编辑:
我更喜欢获取背景色的残差。

如果要获取背景色代码,请尝试以下操作:

if (textView.getBackground() instanceof ColorDrawable) {
    ColorDrawable cd = (ColorDrawable) textView.getBackground();
    int colorCode = cd.getColor();
}

回答:

我们不能使用像color.red或color.white这样的常量

我们需要弄清楚

int intID = (ColorDrawable) holder.tvChoose.getBackground().getColor();

表示它,我们有颜色的假ID。getColor()只能在API级别高于11的情况下工作,因此您可以使用此代码从一开始就支持它。 我使用的反射低于API级别11

 public static int getBackgroundColor(TextView textView) {
        Drawable drawable = textView.getBackground();
        if (drawable instanceof ColorDrawable) {
            ColorDrawable colorDrawable = (ColorDrawable) drawable;
            if (Build.VERSION.SDK_INT >= 11) {
                return colorDrawable.getColor();
            }
            try {
                Field field = colorDrawable.getClass().getDeclaredField("mState");
                field.setAccessible(true);
                Object object = field.get(colorDrawable);
                field = object.getClass().getDeclaredField("mUseColor");
                field.setAccessible(true);
                return field.getInt(object);
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

如果您正在使用AppCompat,请使用以下命令:

ViewCompat.getBackgroundTintList(textView).getDefaultColor();

旁注:如果您强制转换为
ColorDrawable
,请小心,因为在Kotlin中,它可能会引发
ClassCastException:android.graphics.drawable.RippleDrawable无法强制转换为android.graphics.drawable.ColorDrawable

    val cd = view.background as ColorDrawable
    val colorCode = cd.color

我编辑我的问题:我如何从中得到颜色的剩余?我尝试了这个,但是在你回答的第一行之后,我得到的cd是空的。你如何设置你的文本视图的背景?要使用这段代码,它必须是颜色,而不是渐变或其他类型的绘图,因为我在第一次出现时没有设置背景。我修复了thet,但现在是cd.getColor()返回我-1小心:这可能引发
异常
java.lang.ClassCastException:android.graphics.drawable.RippleDrawable不能强制转换为android.graphics.drawable.ColorDrawable
,或者我正在互联网上搜索一点,但似乎没有办法从xml定义的颜色中获得这样的id。您可能应该以编程方式更改应用程序并管理背景颜色,也许可以在onClick事件期间跟踪颜色更改。给定视图使用的颜色可能没有资源ID。背景的res ID为
R.attr.background
,对应于主题或样式中的
。您可以,并将其与TextView的颜色进行比较,以查看其是否匹配。