TextView setTextColor() 不起作用

问题描述 投票:0回答:7

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

    <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 默认将其颜色设置为红色。这有效。

在 Java 中创建元素时,我这样做

lagerstandText.setText("bla");

对于某些元素我也这样做

lagerstandText.setTextColor(R.color.red);

和其他颜色。虽然我没有调用 setTextColor() 的元素是红色的,但无论我选择哪种颜色(即使它再次是相同的红色),所有其他元素都是灰色的。

这是为什么?

android colors textview
7个回答
237
投票

文档对此并不是很详细,但是在调用

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));

35
投票

因此,有很多方法可以完成此任务。

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));

4
投票

1.您喜欢的标准颜色请选择下面的。

textview.setTextColor(Color.select_color)

2.这里想要使用自定义颜色将其添加到color.xml文件中

textview.setTextColor(getResources().getColor(R.color.textbody));

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

subText.setTextColor(Color.rgb(255,192,0));

2
投票

为了将来参考,您可以使用以下内容:

String color = getString(Integer.parseInt(String.valueOf(R.color.my_color)));
my_textView.setTextColor(Color.parseColor(color));

这样您就可以利用您的颜色资源。


1
投票
textView.setTextColor(Color.RED);

0
投票

R
类中定义的特定颜色(在xml布局中定义)的整数id不能作为参数传递给
setTextColor()
类的
View
方法。 您必须通过以下代码行获取
setTextColor()
的参数:

int para=getResources().getColor(R.color.your_color,null);
view.setTextColor(para,null);

方法

getColor(int id)
已被弃用...而是使用
getColor(int id,Resources.Theme theme)
,如上面的代码行所示。

The `second parameter( theme )` can be null

0
投票

我访问 www.textnow.com/ 时出现错误。

错误代码:1020 射线 ID:80d8a0774ad55dd8 国家: 越南 数据中心:HKG10 IP地址:123.31.246.139 时间戳: 2023-09-28 02:41:20 UTC

© www.soinside.com 2019 - 2024. All rights reserved.