Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checkboxes in a ListView - When I select the first, it checks the last and vice versa

I've set up a ListView that contains a Checkbox in each row (along with a TextView). For some reason, when I "check" one of the boxes, it seems to "check" whichever box is opposite in the ListView (i.e. when selecting the top box, the bottom checkbox becomes selected while the top remains unchecked.

I realize there isn't any code here to work with, but I was just wondering if this is a general problem? If not, I can try to post some code. Thanks!

like image 406
jonstaff Avatar asked Dec 14 '11 20:12

jonstaff


1 Answers

Views are recycled in a ListView. That's why some are checked when you think shouldn't be.

Here's the deal: The checkbox has no idea which item in your adapter it represents. It's just a checkbox in a row in a ListView. You need to do something to "teach" the rows which item in your data set they are currently displaying. So, instead of using something as simple as a String array as the data for your adapter, create a new model object that stores the state of the checkbox in it. Then, before you return the row in getView(), you can do something like:

//somewhere in your class
private RowData getData(int position) {
return(((MyAdapter)getListAdapter()).getItem(position)); 
}



 //..then in your adapter in getView()

    RowData object = getModel(position);

     if(object.isChecked()) {
       myCheckbox.setChecked(true);
     } else {
       myCheckbox.setChecked(false);
      }

     //then retun your view.
like image 136
LuxuryMode Avatar answered Sep 29 '22 21:09

LuxuryMode