kspacja
kspacja

Reputation: 4874

Text color in TextViews of ListView setted by selector works only in "normal" state

I create ListView and my own ListAdapter. I use simple_list_item_2. I want to change color of text for each state. There is code of dark.xml below:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">  
    <item android:state_selected="true" android:color="@color/selectedTextListColor"/>
    <item android:state_focused="true" android:color="@color/selectedTextListColor"/>
    <item android:state_pressed="true" android:color="@color/selectedTextListColor"/>
    <item android:color="@color/textListColor"/>
</selector>

Next it is part of code when I try to set that functionality. I think there is a problem.

ArrayAdapter<Element> adapter = new ArrayAdapter<Element>(instance, android.R.layout.simple_list_item_2, songsArray){

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        TwoLineListItem row;

        if (convertView == null) {
             LayoutInflater inflater = (LayoutInflater)getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
             row = (TwoLineListItem)inflater.inflate(android.R.layout.simple_list_item_2, null);

             } else {                               
             row = (TwoLineListItem)convertView;

                        }


        Element song = songsArray[position];
        String data = song.text();

        int dashIndex = data.indexOf("-");

        TextView text2 = row.getText2();
        text2.setText(data.substring(0, dashIndex-1).trim());
        text2.setTextSize(12.0f);
        text2.setPadding(10, text2.getPaddingTop(), text2.getPaddingRight(), text2.getPaddingBottom());

        TextView text1 = row.getText1();
        text1.setText(data.substring(dashIndex+1).trim());                          
        text1.setTextSize(18.0f);
        text1.setPadding(10, text1.getPaddingTop(), text1.getPaddingRight(), text1.getPaddingBottom());

        text1.setTextColor(getResources().getColor(R.color.dark));                  

        return row;
    }

};

It still works in such a way, that text has color red and it didn't change on press. Could you tell correct way? Pay attention on line

text1.setTextColor(getResources().getColor(R.color.dark)); 

I think there is my mistake.

Upvotes: 1

Views: 841

Answers (2)

kspacja
kspacja

Reputation: 4874

text1.setTextColor(getResources().getColorStateList(R.color.dark));

That was my problem. Now it works great.

Upvotes: 2

Blackbelt
Blackbelt

Reputation: 157457

Force the state inside the onListItemClik(). For instance:

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    v.setSelected(true);

}

Upvotes: 0

Related Questions