android - 如何动态改变TextView的背景颜色?

标签 android textview background-drawable

我已经提交了this question并使用 circle.xml(在 res/drawable 中)为 TextView 实现了圆形背景,并将其设置为 TextView 的 android:background="@drawable/circle"。但是我需要的是,我需要通过代码动态设置背景颜色。就像 Lollipop 联系人应用程序如下所示

enter image description here

我怎样才能做到这一点?如上图所示,我始终需要圆形的 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/

相关文章:

java - ListView 中文本开头的空白

android - 如何限制 TextView 在 Android 中仅允许使用字母数字字符

string - 在不同 View 上显示输入文本

wpf - 在 WPF 中显示大文本的最佳方式?

android - 如何修复横向截断的自定义 SearchView 背景?

java - 在Android中,什么线程可运行传递给Executors.newSingleThreadScheduledExecutor运行?

android - 显示一组对象,一次通过一个对话框显示一个对象...而不是多个对话框

java - Android-Magento-如何使用XML-RPC在Android中获取多个产品的详细信息

android - 可通过代码绘制圆角