SetTextColor of TextView programmatically

允我心安 提交于 2020-01-03 04:34:05

问题


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>

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.

I change the color like this:

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

回答1:


Solved it!

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);
                            } 



回答2:


if your xml file is saved at /res/row.xml then you reference it with R.color.row

TextView tl = (TextView) v.findViewById(R.id.textlabel);
tl.setTextColor(R.color.row);


来源:https://stackoverflow.com/questions/7548653/settextcolor-of-textview-programmatically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!