14 comments on “SelectableListView – Make selection work!

  1. Hello,
    Thx for the tip, but for me convertView in getView is always null for the 1st item. any idea?

    for example :

    if (currItem.isItemSelected) {
    convertView.setBackgroundColor(Color.GREEN);
    } else {
    if(convertView!=null){
    convertView.setBackgroundColor(Color.WHITE);
    }
    }

    the 1st item is not white

    • Hey there,

      That’s actually my fault, the setBackgroundColor should be on the currView, and not on the convertView. Fixed it! The convertView is suppose to be null for the first few items on the list. Why? because of the way the recycling mechanism works. You can check that link that I gave somewhere on this post about that.

    • Why the doubt? In this post I gave an example of a new list adapter, implementing this feature. Maybe I don’t understand what you mean…please explain more about what do you want to do

  2. Hey Udinic, You have given a nice article/tutorial for the the purpose I am looking to achieve. Somehow, after implementing you steps above, my listView only is not getting updated. I know I have messed up with my code (which is quite large). I need a favor from you. It would be great If you can give the whole sample application with this custom adapter implemented. Please let me know if it is possible.

  3. You can also assign a selector xml file as the background drawable for the list item rather than doing it in java. Even easier.

    • Due to the recycling nature of the list items on the list, this option will not work. If you’ll set a background upon press, that data will be lost as soon as you scroll that item outside the visible area of the list.
      Even worse than that – some other unrelated list item will get that data (objects recycling..) and it’ll look like the user has pressed it.

  4. Hi,

    This is really cool and helped me a lot. I have one query though:

    I want to do the selecting on long press, which works roughly the same – the only issue is that the default highlight that you get when you press the list item isn’t done (how it normally goes blue then back to black when you take your finger off the screen again). I think that this is because of the else part of the if statement setting the non selected ones to black regardless of the pressed state.

    If you know how I could hook into that to get the default press behavour back, that would be awesome. If not – thanks anyway for the rest.

  5. the else{ currView.setBackgroundColor(Color.BLACK);} was a big help to me.

    I modified slightly but works for me.

Leave a comment