为textView动态设定字体颜色

今天碰到一个问题,想要在程式中为textView设定字体颜色。可是setTextColor总是不起作用,于是查了一些资料。
虽然最后发现没有设定成功是因为我程式的问题,
因为是要设定桌面上GridView中的项目的textView的字体颜色,利用

View convertView = LayoutInflater.from(context).inflate(R.layout.grid, null);
TextView tv = (TextView) convertView.findViewById(R.id.name);
tv.setTextColor(Color.RED);

完全没有作用。原因是通过这种方式无法设定GridView的内容,要在BaseAdapter中的getView中进行设定。
虽然绕了一圈发现问题是我这边,还是把查到的内容总结如下。
//============================================================
网上有有人问同样的问题:

tv.setTextColor(color.blue_light);

colors.xml中:

<?xml version="1.0" encoding="utf-8"?>
<resources>
  <color name="blue_light">#2D9DC8</color>
  <color name="blue_dark">#314d61</color>
  <color name="white">#FFFFFF</color>
  <color name="green_light">#308A24</color>
  <color name="black">#000000</color>
  <color name="black_light">#333</color>
  <color name="grey_light">#A1A1A1</color>
</resources>

无法设置字体颜色。
解决方法:

setTextColor(getResources().getColor(R.color.blue_light));

// ============================================================
因为我们设置setTextColor参数为int型,如果传过来都是字符型的参数像"#FFFFFFFF"如何转成0xFFFFFFFF格式的int型呢?
不用做字符串的操作,有一种更加简单的办法:

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

这样的话,可以设置一个array String的resource,根据位置进行颜色的设定。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <!-- 当新添加背景页面时,同时要添加图标下文字的颜色设定 -->
    <string-array name="item_text_color">
        <item>#ffffff00</item> <!-- 黄色 -->
        <item>#ff000000</item> <!-- 黑色 -->
    </string-array>
</resources>

还有另外的两种颜色设置的办法:

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

posted @ 2012-07-03 19:44  日光之下无新事  阅读(1943)  评论(0编辑  收藏  举报