Android ListView with Checkbox: automatically unchecks
Asked Answered
R

2

6

I've got a ListView with a custom BaseAdapter. The list items contain CheckBoxes that need to represent a property from a database.

I use CheckBox.setOnCheckedChangeListener with a new OnCheckedChangeListener to detect changes, so I can change the database based on the current state of the CheckBox. Pretty straightforward stuff so far.

However, when scrolling further down the list, previously checked CheckBoxes get unchecked. I suspect this happens as soon as the views are recycled (I'm using the convertView/ViewHolder technique).

How can I stop this? What's going wrong?

Thanks in advance.


Edit: To make things a bit clearer, the problem is that recycling views somehow calls OnCheckedChangeListener#onCheckedChanged(buttonView, isChecked) with isChecked == false.

Rogerrogerio answered 3/5, 2010 at 9:26 Comment(0)
R
11

Apparently the problem was that, by getting the checkbox using convertView.findViewById(), the onCheckedChangeListeners were still intact if the view was recycled. Calling checkbox.setOnCheckedChangeListener(null) did the trick.

Rogerrogerio answered 3/5, 2010 at 15:15 Comment(4)
I was having the same problem when using checkbox in the child view of an ExpandableListView, and your trick worked for me as well. I had to put this in getChildView(..), where I check if we are recycling (i.e., convertView is not null), and set the OnCheckedChangeListener of the checkbox to null in that case. Thanks for the solution.Shirleenshirlene
I am having a similar problem, but I dont know how to fix it: #4586942 any ideas?Conyers
I know its an old thread but I have the same problem.It seems like the onCheckedChangeListener method is called randomly. What exactly do you mean by checkbox.setOnCheckedChangeListener(null)? Its the null that confuses me! Have a look at my code if you want: #5444855Bumbling
I had the same issue as @SamikR, and this fixed it! Thanks!Cordova
M
0

Use a boolean array to store the checked state of each list item, record the changes inside setOnCheckedChangeListener(), then call setChecked() after setOnCheckedChangeListener().

Mammary answered 19/8, 2019 at 21:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.