TextView setTextColor()不工作 [英] TextView setTextColor() not working

查看:346
本文介绍了TextView setTextColor()不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我以编程方式创建一个列表(没有ListView,只是将它们添加到父元素):

I programmatically create a list (no a ListView, just adding them to the parent) of such elements:

    <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" 
    android:orientation="vertical" android:layout_weight="1">
    <TextView android:id="@+id/filiale_name"
    android:layout_width="fill_parent" android:layout_height="wrap_content"/>
    <TextView android:id="@+id/lagerstand_text"
    android:layout_width="fill_parent" android:layout_height="wrap_content"
    android:textSize="10sp" android:textColor="@color/red"/>
</LinearLayout>

此外,我在values / colors.xml中定义了一些颜色。正如你所看到的,默认情况下,ID为lagerstand_text的TextView将其颜色设置为红色。

Also, I have defined some colors in values/colors.xml. As you see, the TextView with id "lagerstand_text" has set it's color to red by default. That works.

在Java中创建元素时,我会

When creating the elements in Java, I do

lagerstandText.setText("bla");

而且对于某些元素,我也会

and for some elements also I do

lagerstandText.setTextColor(R.color.red);

和其他颜色。虽然我不叫setTextColor()的元素是红色的,所有其他的都是灰色的,不管我选择了哪种颜色(即使它是同样的红色)。

and other colors. While the elements on which I don't call setTextColor() are red, all others are grey, no matter which color I chose (even if it's the same red again).

为什么?

推荐答案

文档不是很详细,但是你不能只使用R.color整数当调用 setTextColor 时。您需要调用 getResources()。getColor(R.color.YOURCOLOR)才能正确设置颜色。

The documentation is not very verbose about this, but you cannot use just the R.color integer when calling setTextColor. You need to call getResources().getColor(R.color.YOURCOLOR) to set a color properly.

使用以下内容以编程方式设置文字的颜色:

Use the following to set color of your text programmatically:

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

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

Starting with the support library 23 you have to use the following code, because getColor is deprecated:

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

这篇关于TextView setTextColor()不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆