以编程方式TextView的SetTextColor [英] SetTextColor of TextView programmatically

查看:170
本文介绍了以编程方式TextView的SetTextColor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在每行中都有一个带有TextView的ListView.我在row.xml中设置了默认的color.xml

I have a ListView with a TextView in each row. I have a default color.xml with is set in the row.xml

我在不同的州有不同的颜色

I have different colors for different states

<selector xmlns:android="http://schemas.android.com/apk/res/android" >
    <!--  pressed -->
    <item 
        android:color="#ffffff"
        android:state_pressed="true"/>
    <!-- focused -->
    <item android:state_selected="true"
          android:color="#8b8989"/> 
    <!-- default -->
    <item android:color="#ffffff"/> 

</selector>

这就像一个护身符.但是,当我试图更改代码中某些行的颜色时,这似乎不起作用. second_color.xml看起来相同,但是颜色不同.颜色已更改,但是对于其他状态(不是默认状态),没有任何变化.

This works like a charm. But when Im trying to change the color for some rows in code, this doesn't seem to work. The second_color.xml looks just the same, but with different colors. The color is changed, but for the other states (not default) nothing changes.

我这样改变颜色:

TextView tl = (TextView) v.findViewById(R.id.textlabel);
tl.setTextColor(getContext().getResources().getColor(R.color.second_color));

推荐答案

解决了!

要在代码中进行设置,需要创建一个ColorStateList.

In order to set this in code it's required to create a ColorStateList.

ColorStateList cl = null;
                            try {
                               XmlResourceParser xrp = getResources().getXml(R.color.live_color);
                               cl = ColorStateList.createFromXml(getResources(), xrp);
                            } catch (Exception ex) {}

                            if(cl != null){

                                tl.setTextColor(cl);
                            } 

这篇关于以编程方式TextView的SetTextColor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆