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

dev*_*dev 3 android textview background-drawable

我已经提到了这个问题,并使用circle.xml (在res/drawable中)为TextView实现循环背景,并将其设置android:background="@drawable/circle"为TextView.但我需要的是,我需要通过代码动态设置背景颜色.就像棒棒糖联系应用程序,如下所示

在此输入图像描述

我该如何实现这一目标?我需要圆形的TextView背景,如上图所示

Hus*_*eky 9

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

textView.setBackgroundColor(Color.parseColor("#f44336"));
Run Code Online (Sandbox Code Playgroud)

要么

textView.setBackgroundColor(Color.RED);
Run Code Online (Sandbox Code Playgroud)

要么

textView.setBackgroundColor(Color.rgb(255, 0, 0));
Run Code Online (Sandbox Code Playgroud)

要么

textView.setBackgroundColor(getColor(R.color.red_color));
Run Code Online (Sandbox Code Playgroud)

以及许多其他方式......

编辑:

如果要更改可绘制文件中定义的TextView背景颜色,请执行以下操作:

GradientDrawable:

GradientDrawable tvBackground = (GradientDrawable) textView.getBackground();
tvBackground.setColor(Color.parseColor("#f44336"));
Run Code Online (Sandbox Code Playgroud)

StateListDrawable:

StateListDrawable tvBackground = (StateListDrawable) textView.getBackground();
tvBackground.setColorFilter(Color.parseColor("#f44336"), PorterDuff.Mode.SRC_ATOP);
Run Code Online (Sandbox Code Playgroud)

但是,如果您不想设置颜色过滤器,可以按照此链接中的答案分别获取每个州的drawable .