TextView setTextColor()不起作用

did*_*_X8 67 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>
Run Code Online (Sandbox Code Playgroud)

另外,我在values/colors.xml中定义了一些颜色.如您所见,ID为"lagerstand_text"的TextView默认将其颜色设置为红色.这样可行.

用Java创建元素时,我做到了

lagerstandText.setText("bla");
Run Code Online (Sandbox Code Playgroud)

对于某些元素,我也这样做

lagerstandText.setTextColor(R.color.red);
Run Code Online (Sandbox Code Playgroud)

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

这是为什么?

Sun*_*hoo 204

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

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

textView.setTextColor(getResources().getColor(R.color.YOURCOLOR));
Run Code Online (Sandbox Code Playgroud)

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

textView.setTextColor(ContextCompat.getColor(context, R.color.YOURCOLOR));
Run Code Online (Sandbox Code Playgroud)

  • 你也可以用Color.(这里是红绿黑蓝黄等)setTextColor(Color.RED) (13认同)
  • 好的,那很有效.在这种情况下,API文档可能会更冗长...... (2认同)

dug*_*ggu 31

因此,有很多方法可以完成这项任务.

1.

int color = Integer.parseInt("bdbdbd", 16)+0xFF000000;
textview.setTextColor(color);
Run Code Online (Sandbox Code Playgroud)

2.

textView.setTextColor(getResources().getColor(R.color.some_color));
Run Code Online (Sandbox Code Playgroud)

3.

textView.setTextColor(0xffbdbdbd);
Run Code Online (Sandbox Code Playgroud)

4.

textView.setTextColor(Color.parseColor("#bdbdbd"));
Run Code Online (Sandbox Code Playgroud)

5.

textView.setTextColor(Color.argb(a_int, r_int, g_int, b_int));
Run Code Online (Sandbox Code Playgroud)