0
votes

I'm using a simple_list_item_activated_1 list with multiple selection possible.

I want to change the background color of any selected items.

Setting: android:listSelector="@color/highlight" doesn't work as when I first click on the list, the correct color (highlight which is a red) is shown, but then it is immediately changed to the default green color (see image below)

I've tried creating a custom xml (search_background.xml) in drawable for background in drawable:

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

And called this with: android:listSelector="@drawable/search_background"

Again when I first click on the list, the correct color (highlight which is a red) is shown, but then it is immediately changed to the default green color.

I guess I'm not including the state where the list item has been selected. Looking at: Android state lists. I can't seem to find it and would appreciate any guidance.

enter image description here

ANSWER: Set background color for selected and unselected states in item listener:

 // ListView Item Click Listener
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view,
                                int position, long id) {


            int itemPosition = position;
            if (!listView.isItemChecked(position)){    
// ListView item Clicked - previously selected                                           view.setBackgroundColor(Color.parseColor("#000000"));

            }
            else {
                // ListView Clicked item - previously not selected                 
                view.setBackgroundColor(Color.parseColor("#CC3300"));
            }
        }
    });
1
Can you add this item: <item android:drawable="@color/background" />Christopher
Hi Christopher, I presume you mean add this to my search_background.xml. Unfortunately this has no effectNicholas Farmer

1 Answers

1
votes

All those states you have described above are mostly useful at the moment when view has been clicked.

You have to implement onClick listener in your ListView adapter to save clicked items and set proper background for selected & unselected items.

Here is a reference to how you could show single selected item in your ListView https://stackoverflow.com/a/16978159/3816129