如何获取TextView的背景颜色?

15

我该如何获取TextView的背景颜色?

当我按下TextView时,我想根据当前使用的背景颜色来更改背景颜色。

TextView没有像这样的方法:

getBackgroundResource()

编辑: 我更喜欢获取背景颜色的resId。


我在互联网上搜索了一下,但似乎没有办法从XML定义的颜色中获取这样的ID。也许你应该改变你的应用程序,通过编程方式管理背景颜色,可能在onClick事件期间跟踪颜色变化。 - Cob013
给定视图所使用的颜色可能没有资源ID。背景的资源ID是R.attr.background,它对应于您的主题或样式中的<item name="android:background">。您可以从主题中获取颜色值,并将其与TextView的颜色进行比较,以查看它是否匹配。 - jpaugh
5个回答

21

如果您想获取背景色的颜色代码,请尝试以下方法:

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

我编辑了我的问题:我如何从中获取颜色的resId? - OrSmolnik
我尝试了这个,但在你回答的第一行后,我得到了“cd is null”的错误。 - OrSmolnik
你如何设置TextView的背景?要使用此代码,它必须是颜色,而不是渐变或其他类型的Drawable。 - Gokhan Arik
好的,非常奇怪。如果我先将背景设置为color.black,getColor()返回给我的是其他数字(不是-1),但它仍然不是相同的resID color.black。我的“if”是为了检查背景是否等于白色背景,因此我将“if(cd.getColor()==color.white)”替换为“if(cd.getColor()==-1)”。这样就可以了! - OrSmolnik
1
请注意:这可能会抛出一个“异常”:“java.lang.ClassCastException: android.graphics.drawable.RippleDrawable无法转换为android.graphics.drawable.ColorDrawable”。 - Albert Vila Calvo
显示剩余3条评论

2

在Kotlin中:

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

1
如果您正在使用AppCompat,请使用以下内容:
ViewCompat.getBackgroundTintList(textView).getDefaultColor();

注意:如果你将其转换为ColorDrawable,请小心,因为它可能会抛出一个ClassCastException:android.graphics.drawable.RippleDrawable cannot be cast to android.graphics.drawable.ColorDrawable异常。


0

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

0

答案:

我们不能像 color.red 或 color.white 那样使用常量。

我们需要弄清楚如何

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

表示它,我们有颜色的假身份证


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接