-1

I want to do this : I have a list whose colors of every two items are different and want to select the item that was clicked. The item that is selected is highlighted but the old color returns after it is released

I did this : artists_list_background_alternate.xml :

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

 <item
     android:state_selected="false"
     android:state_pressed="false"
     android:drawable="@color/sign_out_color" />

 <item android:state_pressed="true"
     android:drawable="@color/survey_toplist_item" />

 <item android:state_selected="true"
     android:state_pressed="false"
     android:drawable="@color/survey_toplist_item" />

</selector> 

artists_list_backgroundcolor.xml :

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

Java File Code ::

 @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = convertView;
        if (view == null) {
            view = lInflater.inflate(R.layout.listitem, parent, false);
        }

        if (position % 2 == 0) {
            view.setBackgroundResource(R.drawable.artists_list_backgroundcolor);
        } else {
            view.setBackgroundResource(R.drawable.artists_list_background_alternate);
        }

        ((TextView) view.findViewById(R.id.heading)).setText(data.get(position));

        return view;
    }


  ListView lvMain = (ListView) findViewById(R.id.list);
        lvMain.setAdapter(adapter);

Layout xml ::

 <ListView
        android:id="@+id/list"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:cacheColorHint="#00000000"
        android:dividerHeight="1dp" />

And I don't know what I did wrong

Jaymin
  • 2,879
  • 3
  • 19
  • 35
Krzysztof Pokrywka
  • 1,356
  • 4
  • 27
  • 50

1 Answers1

0

In order to make an item highlighted, you need to provide choiceMode for your ListView. For example:

android:choiceMode="singleChoice"

Also, add a color for state android:state_activated="true" in your selector.

waqaslam
  • 67,549
  • 16
  • 165
  • 178