如何以编程方式将文本颜色设置为文本视图

时间:2011-12-12 09:39:46

标签: android textview background-color

如何以编程方式将文本视图的文本颜色设置为#bdbdbd

4 个答案:

答案 0 :(得分:552)

使用,..

Color.parseColor("#bdbdbd");

mTextView.setTextColor(Color.parseColor("#bdbdbd"));

或者,如果您在资源的color.xml文件中定义了颜色代码而不是

(来自API> = 23)

mTextView.setTextColor(ContextCompat.getColor(context, R.color.<name_of_color>));

(对于API&lt; 23)

mTextView.setTextColor(getResources().getColor(R.color.<name_of_color>));

答案 1 :(得分:213)

很棒的答案。添加one从Android资源xml加载颜色,但仍然以编程方式设置它:

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

请注意,从API 23开始,不推荐使用getResources().getColor()。改为使用:

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

其中所需颜色在xml中定义为:

<resources>
  <color name="some_color">#bdbdbd</color>
</resources>

更新:

  

此方法在API级别23中已弃用。使用getColor(int,Theme)   代替。

检查this

答案 2 :(得分:34)

yourTextView.setTextColor(color);

或者,在您的情况下:yourTextView.setTextColor(0xffbdbdbd);

答案 3 :(得分:20)

TextView tt;
int color = Integer.parseInt("bdbdbd", 16)+0xFF000000;
tt.setTextColor(color);

tt.setBackgroundColor(Integer.parseInt("d4d446", 16)+0xFF000000);

tt.setBackgroundColor(Color.parseColor("#d4d446"));

请参阅:

Java/Android String to Color conversion