"TextView setTextColor() 不起作用"

12 浏览
0 Comments

"TextView setTextColor() 不起作用"

我通过编程方式创建了一个元素列表(不是ListView,只是将它们添加到父级中):

    
    
    

此外,我在values/colors.xml中定义了一些颜色。正如您所看到的,带id“lagerstand_text”的TextView默认设置为红色。它有效。

当我在Java中创建元素时,我执行

lagerstandText.setText("bla");

对于一些元素,我也会执行

lagerstandText.setTextColor(R.color.red);

以及其他颜色。 当我不调用setTextColor()的元素是红色的,所有其他元素是灰色的,无论我选择了哪种颜色(即使它是同样的红色)。

为什么会这样?

admin 更改状态以发布 2023年5月25日
0
0 Comments

所以,有许多方法可以完成此任务。

1.

int color = Integer.parseInt("bdbdbd", 16)+0xFF000000;
textview.setTextColor(color);

2.

textView.setTextColor(getResources().getColor(R.color.some_color));

3.

textView.setTextColor(0xffbdbdbd);

4.

textView.setTextColor(Color.parseColor("#bdbdbd"));

5.

textView.setTextColor(Color.argb(a_int, r_int, g_int, b_int));

0
0 Comments

文档对此没有详细说明,但是在调用setTextColor时,您不能仅使用R.color整数。您需要调用getResources().getColor(R.color.YOURCOLOR)来正确设置颜色。

使用以下代码以程序方式设置文本的颜色:

textView.setTextColor(getResources().getColor(R.color.YOURCOLOR));

从支持库23开始,您必须使用以下代码,因为getColor已被弃用:

textView.setTextColor(ContextCompat.getColor(context, R.color.YOURCOLOR));

0