0

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));
Cœur
  • 37,241
  • 25
  • 195
  • 267
johan
  • 6,578
  • 6
  • 46
  • 68

2 Answers2

7

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);
                            } 
johan
  • 6,578
  • 6
  • 46
  • 68
0

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);
nock
  • 111
  • 1
  • 1
  • 9
  • My row is set in row.xml where color.xml is assigned as color. However I want to change it to second_color.xml is some occasions... – johan Sep 25 '11 at 21:36
  • I did find a solution...will post it below. Thanks anyway! – johan Sep 25 '11 at 21:42
  • 3
    Actually it does not work, the right solution is `t1.setTextColor(context.getResources().getColor(R.color.row));` – louiscoquio Mar 23 '12 at 09:07