如何动态更改TextView的背景颜色?

3
我参考了这个问题,使用circle.xml(在res/drawable中)为TextView实现了圆形背景,并将其设置为android:background="@drawable/circle"。但我需要的是,我需要通过代码动态设置背景颜色。就像Lollipop联系人应用程序中所示的那样。如下图所示:

enter image description here

我该如何实现这一点?我需要始终以上图所示的圆形形状设置TextView背景。
3个回答

9

您可以通过多种方式更改TextView的背景颜色,例如:

textView.setBackgroundColor(Color.parseColor("#f44336"));

或者

textView.setBackgroundColor(Color.RED);

或者

textView.setBackgroundColor(Color.rgb(255, 0, 0));

或者

textView.setBackgroundColor(getColor(R.color.red_color));

还有许多其他方式...

编辑:

如果您想更改在可绘制文件中定义的TextView背景颜色,请按照以下方式进行操作:

GradientDrawable:

GradientDrawable tvBackground = (GradientDrawable) textView.getBackground();
tvBackground.setColor(Color.parseColor("#f44336"));

StateListDrawable:

StateListDrawable tvBackground = (StateListDrawable) textView.getBackground();
tvBackground.setColorFilter(Color.parseColor("#f44336"), PorterDuff.Mode.SRC_ATOP);

但如果您不想设置颜色过滤器,可以按照此链接中的答案分别获取每个状态的可绘制对象。


是的,所有这些都是可以用来实现所需效果的选项。我正要添加其余部分。 - Akah
但这并没有给我圆形背景形状。它只改变了背景颜色。圆形背景将消失,新的颜色将显示在方形背景中。 - dev
你在问题中没有提到你想要它呈圆形。 - Hussein El Feky
GradientDrawable对TextView无效。出现错误:java.lang.ClassCastException:android.graphics.drawable.StateListDrawable无法转换为android.graphics.drawable.GradientDrawable。 - drod
@drod 看起来你正在使用 StateListDrawable 而不是 GradientDrawable。StateListDrawable 可以有许多背景状态,因此没有明确的背景。所以请尝试我的更新答案。 - Hussein El Feky
在 Kotlin 中有没有一行代码可以实现这个? - nmu

2

我想您希望了解如何生成随机颜色并将其设置为文本视图的背景颜色。那么,有很多方法。例如:

textview.setBackgroundColor(Color.rgb((int) (Math.random() * 255), (int) (Math.random() * 255), (int) (Math.random() * 255)));

是的,但这不能用于生成随机颜色。new Color((int)(Math.random() * 0x1000000)) 这个语句是无效的。 - dev

1
我的文本视图具有一个圆形的形状,定义如下:
// circleshape.xml
<?xml version="1.0" encoding="utf-8"?> 
<shape xmlns:android="schemas.android.com/apk/res/android"; android:shape="oval"> 
<solid android:color="@android:color/darker_gray" /> 
<corners android:bottomRightRadius="8dp" android:bottomLeftRadius="8dp" android:topRightRadius="8dp" android:topLeftRadius="8dp"/> 
</shape>

我将其应用于TextView,使用background="@drawable/circleshape",这使得TextView成为圆形。现在使用以下代码:
GradientDrawable tvBackground = (GradientDrawable) viewHolder.userInitialsText.getBackground();

//myHexColorCode  is like "0xff00ff"
tvBackground.setColor(Color.parseColor(myHexColorCode));

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