本文介绍了如何在代码中设置TextView的文字颜色?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 XML 中,我们可以通过 textColor 属性设置文本颜色,例如 android:textColor="#FF0000".但是如何通过编码来改变呢?

In XML, we can set a text color by the textColor attribute, like android:textColor="#FF0000". But how do I change it by coding?

我尝试了类似的方法:

holder.text.setTextColor(R.color.Red);

holder 只是一个类,textTextView 类型.红色是在字符串中设置的 RGB 值 (#FF0000).

Where holder is just a class and text is of type TextView. Red is an RGB value (#FF0000) set in strings.

但它显示不同的颜色而不是红色.我们可以在 setTextColor() 中传递什么样的参数?在文档中,它说 int,但它是资源引用值还是其他什么?

But it shows a different color rather than red. What kind of parameter can we pass in setTextColor()? In documentation, it says int, but is it a resource reference value or anything else?

推荐答案

你应该使用:

holder.text.setTextColor(Color.RED);

您当然可以使用 Color 类中的各种函数来获得相同的效果.


You can use various functions from the Color class to get the same effect of course.

  • Color.parseColor (手动)(就像 LEX 使用的那样)

  • Color.parseColor (Manual) (like LEX uses)

text.setTextColor(Color.parseColor("#FFFFFF"));

  • Color.rgbColor.argb (手动 rgb) (Manual argb) (就像 Ganapathy 使用的那样)

  • Color.rgb and Color.argb (Manual rgb) (Manual argb) (like Ganapathy uses)

    holder.text.setTextColor(Color.rgb(200,0,0));
    holder.text.setTextColor(Color.argb(0,200,0,0));
    

  • 当然,如果你想在 XML 文件中定义你的颜色,你可以这样做:

  • And of course, if you want to define your color in an XML file, you can do this:

    <color name="errorColor">#f00</color>
    

    因为 getColor() 函数已弃用,你需要像这样使用它:

    because the getColor() function is deprecated, you need to use it like so:

    ContextCompat.getColor(context, R.color.your_color);
    

  • 你也可以插入普通的 HEX,像这样:

  • You can also insert plain HEX, like so:

    myTextView.setTextColor(0xAARRGGBB);
    

    首先有 alpha 通道,然后是颜色值.

    Where you have an alpha-channel first, then the color value.

    当然要查看完整的手册,public class Color extends Object.

    Check out the complete manual of course, public class Color extends Object.

    这里也有这段代码:

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

    此方法现已在 Android M 中弃用.但是,您可以从 支持库中的contextCompat,如现在的示例所示.

    This method is now deprecated in Android M. You can however use it from the contextCompat in the support library, as the example now shows.

    这篇关于如何在代码中设置TextView的文字颜色?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

  • 08-03 23:33
    查看更多