TextView setTextColor()无法正常工作


73

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

这是为什么?

Answers:


219

文档不是很冗长,但是在调用时不能仅使用R.color整数setTextColor。您需要致电getResources().getColor(R.color.YOURCOLOR)以正确设置颜色。

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

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

从支持库23开始,您必须使用以下代码,因为不建议使用getColor:

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

2
好的,那行得通。在这种情况下,API文档可能会更加冗长...
didi_X8

13
您也可以使用颜色。(这里是红色,绿色,黑色,蓝色,黄色等)setTextColor(Color.RED)
彼得

感谢您提供的信息...但是此getResources()使我传递了一系列上下文。应该有一些更好的方式来访问全球资源。
Umair 2012年

@Umair在您的Application类上使用静态变量。
kontinuity

@Kontinuity,我读到将上下文保持在静态变量中是内存泄漏的重要根源。
Umair

33

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

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

有没有办法找出特定的颜色值是否会使文本消失?
Christopher Masser

在使用setTextColor(color)之前,我正在调整颜色的亮度。在某些未知情况下,TextView只会在设备上消失(与背景无关)。我想编写一个测试函数,以在“ setTextColor(color)”中使用“ color”之前,先检查“ color”是否为有效的颜色值。
Christopher Masser 2013年

@ChristopherMasser不尝试您说的任何内容??
duggu 2013年

2

为了将来参考,可以使用以下方法:

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

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


2

1.标准颜色,请选择以下颜色。

textview.setTextColor(Color.select_color)

2.这里要使用custwom颜色将其添加到color.xml文件中

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

要么

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

要么

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

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
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.