7

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!

jonstaff
  • 2,672
  • 2
  • 19
  • 18
  • Post your code for the ListView adapter and resource xml – Spidy Dec 14 '11 at 20:52
  • 1
    You should probably post some code, but there is indeed a common general problem (not a bug, but a design thing which a lot of people new to Android don't realize) which likely is what you're running into to do with the way Android ListViews reuse Views to prevent excessive object creation and garbage collection. – kabuko Dec 14 '11 at 20:53
  • My goal is to create a menu that comes up (like on gmail) when the user selects one or more checkboxes. I'm not really sure how to decide which portions of code to post, but when I take out my methods that bring up my "menu" at the bottom, the problem goes away. Any ideas on how to implement garbage collection? – jonstaff Dec 14 '11 at 21:07
  • http://stackoverflow.com/questions/7738527/getting-an-issue-while-checking-the-dynamically-generated-checkbox-through-list/7738854#7738854 – Lalit Poptani Jan 20 '12 at 05:36

1 Answers1

4

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.
LuxuryMode
  • 33,401
  • 34
  • 117
  • 188