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

I created a ListView that contains a checkbox in each row (along with a TextView). For some reason, when I "check" one of the fields, it seems to "check" no matter which field is opposite in the ListView (i.e., when you select the top window, the bottom checkbox is selected, and the top remains unchecked.

I understand that there is no code to work here, but I'm just wondering if this is a common problem? If not, I can try to post some code. Thanks!

+7
source share
1 answer

Representations are processed in ListView. This is why some are checked when you think this should not be.

Here's the deal: the checkbox has no idea which element in your adapter it represents. This is only a checkbox in a row in a ListView. You need to do something to β€œteach” the rows that are currently being displayed in your dataset. Therefore, instead of using something as simple as a String array as data for your adapter, create a new model object that stores the state of the flag. Then, before you return the string to 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. 
+4
source

All Articles