我已经提交了this question并使用 circle.xml
(在 res/drawable 中)为 TextView 实现了圆形背景,并将其设置为 TextView 的 android:background="@drawable/circle"
。但是我需要的是,我需要通过代码动态设置背景颜色。就像 Lollipop 联系人应用程序如下所示
我怎样才能做到这一点?如上图所示,我始终需要圆形的 TextView 背景
最佳答案
您可以通过多种方式更改 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);
但是如果你不想设置颜色过滤器,你可以按照这个link中的答案分别获取每个状态的drawable。 .
关于android - 如何动态改变TextView的背景颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32679854/