Search code examples
androidcheckboxandroid-listviewandroid-viewbinder

ViewBinder setViewValue for ListView item leads to multiple CheckBoxes checked


I'm using a ListView which has:

  1. list item click
  2. CheckBox click

I can save the cursorPosition by using view.setTag(cursor.getPosition()) and I can take necessary action on the checked item but when I scroll down, I see several other CheckBoxes checked(visual only). As a work around I tried setting the view description, saving CheckedBox view ids in list and then iterate to see if CheckBox needs to be shown as checked. But views appear to be reused as I scroll down(same view ids).

How can I only show the actual checked CheckBoxes? Code:

public class MyViewBinder implements ViewBinder {
 public boolean setViewValue(View view, final Cursor cursor, int columnIndex) {
        int viewId = view.getId();
        switch (viewId) {
            case R.id.checkbox:
            view.setTag(cursor.getPosition());
            return true;

            case R.id.....
            .......
        }

Used as:

mySimpleCursorAdapter.setViewBinder(myViewBinder);


Solution

  • I don't have too much experience with the ViewBinder Interface but have you considered using setChoiceMode() on the listview (API reference)? You can set it to CHOICE_MODE_MULTIPLE so that android adds the checkboxes for you. You shouldn't need to worry about maintaining the checked items this way.

    API Demo example.