android - TextView setTextColor()不起作用

标签 android colors textview

我以编程方式创建此类元素的列表(不是 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() 的元素是红色的,但所有其他元素都是灰色的,无论我选择哪种颜色(即使它再次是相同的红色)。

这是为什么呢?

最佳答案

文档对此不是很详细,但在调用 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));

关于android - TextView setTextColor()不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6177273/

相关文章:

java - 如何动态添加可绘制对象到 TextView

java - 如何在android中固定时间后重复任务?

java - 动态合并背景

安卓工作室 : Is it possible to define library module manifest placeholders in main module?

python - 使用 skimage.color.rgb2lab() 将 RGB 三元组转换为 LAB 三元组

c# - 如何读取 XNA 中特定像素的颜色?

android - 将 TextView 放在右下角

android - "IllegalStateException : scrollview can host only one direct child"在一个 LinearLayout 添加

java - Android 以编程方式将图像设置为 TextView 的背景

android - Google Logo 在 Google map 应用(iOS 和 android)中的位置