2011-05-30 83 views
63

我编程方式创建一个列表(没有一个ListView,只是将其添加到父)这样的元素:的TextView setTextColor()不工作

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

而且,我已经定义的值有一些颜色/ colors.xml 。如您所见,ID为“lagerstand_text”的TextView默认将其颜色设置为红色。这样可行。

当创建Java中的元素,我做

lagerstandText.setText("bla"); 

和某些元素还我

lagerstandText.setTextColor(R.color.red); 

等多种颜色。虽然我不称为setTextColor()的元素是红色的,但所有其他元素都是灰色的,无论我选择哪种颜色(即使它再次是相同的红色)。

这是为什么?

+0

如果我的回答是helpfukl你可以接受答案 – 2011-05-30 14:22:09

回答

188

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

好的,那是有效的。在这种情况下,API文档可能会更加冗长...... – 2011-05-30 14:31:38

+12

也可以使用Color。 (这里红色绿色黑色蓝色黄色和其他)setTextColor(Color.RED) – Peter 2011-05-30 14:51:38

+0

感谢您的信息...但这个getResources()让我传递一个上下文链。应该有更好的方法来获取全球资源。 – Umair 2012-09-14 07:25:19

31

所以,有很多方法可以完成这项任务。

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

有没有什么办法找出如果一个特定的颜色值将使文本消失? – 2013-12-02 12:50:56

+0

@ChristopherMasser不明白你想说什么? – duggu 2013-12-02 13:21:44

+0

我在使用setTextColor(color)之前调整颜色的亮度。在某些未知的情况下,TextView会在设备上消失(与背景无关)。我想写一个测试函数来检查“color”是否是一个有效的颜色值,然后在setTextColor(color)中使用它。 – 2013-12-02 15:27:05

0

R类中定义的特定颜色(在XML布局定义)的整数ID不能作为参数传递给View类的setTextColor()方法进行传递。 您必须在下面的代码行获得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 
1

对于未来的参考,你可以使用如下:

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.here要使用custwom颜色添加它color.xml文件

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

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

subText.setTextColor(Color.rgb(255,192,0)); 
相关问题