Skip to content Skip to sidebar Skip to footer

Can't Add Custom Selector To Listview

So, I have a ListFragment with a custom layout which has a custom CursorAdapter that passes custom views to the ListView. The ListView has its choice mode set as MultiChoiceModal.

Solution 1:

In ListView the android:listSelector needs to be a drawable (see documentation), so each item tag in you XML selector file is required to have android:drawable in it. Simply change android:color to android:drawable (you can use the same values) and your current errors should be gone.

Your file after substitution should look like this:

<?xml version="1.0" encoding="utf-8"?><selectorxmlns:android="http://schemas.android.com/apk/res/android"><itemandroid:drawable="@android:color/holo_blue_dark"android:state_pressed="true" /><itemandroid:drawable="@android:color/holo_blue_light"android:state_checked="true" /><itemandroid:drawable="@android:color/holo_blue_bright"android:state_selected="true" /></selector>

Solution 2:

Alright, clearly I should be digging through the source code more often. What I ended up doing was taking the root layout of my list item:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/itemLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

And added one attribute:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/itemLayout"
    android:background="?android:attr/activatedBackgroundIndicator"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

This added the behavior seen in android.R.layout.simple_list_item_activated_1 et al.

Solution 3:

One alternative but lengthier way of doing this is to manually set background color of listView's item in getView() method.

classCustomAdapterextendsBaseAdapter{
...

int selectedID;

publicvoidsetSelectedId(int n)
{
selectedID = n;
}

public View getView(int position, View convertView, ViewGroup parent) {
....
if(position == selectedID)
convertView.setBackgroundColor(someColor);
return convertView;
}

And in listView's OnItemClickListener, add:

customAdapter.setSelectedId(position) 

Though this, method isn't that efficient, however it worked perfectly in my project. Also, avoid using static ViewHolder class or recycling views with this approach.

Post a Comment for "Can't Add Custom Selector To Listview"