views:

63

answers:

1

I have a ListView, and within each list item I have some TextViews and a CheckBox. When I check a CheckBox and my onCheckedChangeListener fires, everything works as it should. However, random other checkboxes get checked once one is checked. Here is an example.

If I click on the first CheckBox: 8 is checked. 15 is checked. 21 is checked. 27 is checked. 33 is checked. 41 is checked. Then if I scroll all the way up, none are checked until 6. The next being 13.

Basically... what is going on?

+2  A: 

It seems that you are reusing the convertView that is passed on the getView() method that you implement.

Android will try to use the same view for different items in a ListView. You will either need to (1) uncheck/check manually the checkbox that is inside the returned item (always call setChecked before returning on getView or (2) don't use convertView, but return a new View from getView.

(1) is recommended, I think.

yuku
OK, so I went with option one. Right before I return the View in getView, I do "checkBox.setChecked(false);". Now, though, when I check a checkbox, scroll down, and scroll back up, it's no longer checked. I know the issue is with my implementation, and not your concept. What am I doing wrong?
Kyle Hughes
When the user checks the checkbox, you need to store that the item's checkbox has been checked, somewhere in your code. For example, if you have 40 items in your ListView, you may have array of boolean to store whether a checkbox of i-th is checked. Then on `getView`, do checkBox.setChecked(booleanArray[position]).
yuku
Maybe it's because it's so late at night, but I cannot figure out how to actually record the position. In the getView method I can have the position, but in the OnClick where I need to actually store the position, I no longer have access to it.
Kyle Hughes
In getView, store the position using setTag() http://developer.android.com/reference/android/view/View.html#setTag(java.lang.Object) and retrieve it later using getTag() in the onClick.
yuku
Ok, that's all been done and it's working well. I can check something, scroll down, scroll back up and have it still checked. However, if I then proceed to uncheck it (and thus remove the true entry from the array), scroll down then back up, it is once again checked.
Kyle Hughes