Hello, dear! I have this question. I have a foliage in which there is a certain checkbox. And here is the code:

public View getView(final int position, View convertView, ViewGroup parent) { CheckBox check = (CheckBox) view.findViewById(R.id.myCheckBox); if(check.getTag() == null) { check.setTag(position); check.setOnCheckedChangeListener(myCheckChangList); } check.setChecked(holders.get(position).isChecked); } private OnCheckedChangeListener myCheckChangList = new OnCheckedChangeListener() { public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { holders.get((Integer) buttonView.getTag()).isChecked = isChecked; } }; 

Everything seems to be great. But the problem is that the handler works not only when I click on the checkbox, but for some reason also when I scroll through the leaves. Let's say I click on the checkbox to make it checked. The listener fires. It seems everything is ok. Then I scroll the list down, then scroll back up and see that the checked box again without a daw. What kind of garbage, I think, and I'm trying to debug it all. I put a breakpoint inside the listener and do the same. When you click on the checkbox breakpoint works - this is logical. However, when I start to scroll through the leaves, it suddenly works too. It turns out that when scrolling with foliage, the android for some reason calls the setChecked method for the checkbox. But why? And why is this happening at all? Thank you in advance!

  • @JuniorTwo, If you are given a comprehensive answer, mark it as correct (click on the check mark next to the selected answer). - Vladyslav Matviienko

1 answer 1

No wonder. When you scroll through the ListView, getView () is called for each item, in which you have this line:

 check.setChecked(holders.get(position).isChecked); 

When this line is executed, onCheckedChanged will be called.
To fix this, you will have to perish a little. For example, change your getView () to:

 public View getView(final int position, View convertView, ViewGroup parent) { CheckBox check = (CheckBox) view.findViewById(R.id.myCheckBox); if(check.getTag() == null) { check.setTag(position); } check.setOnCheckedChangeListener(null); check.setChecked(holders.get(position).isChecked); check.setOnCheckedChangeListener(myCheckChangList); } 

I advise you, before starting to squander from a ListView, read some lessons on it, understand how Adapters work and why ViewHolder is needed, and how Recycling list items occur. Such questions will disappear immediately.