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?
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.
works fine for me
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
final ViewHolder holder;
final Season season = (Season) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.season, parent, false);
holder = new ViewHolder();
holder.title = (TextView) convertView.findViewById(R.id.season_title);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.season_check_box);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.title.setText(season.getTitle());
holder.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
season.setChecked(isChecked);
adapter.notifyDataSetChanged();
}
});
holder.checkBox.setChecked(season.isChecked()); // position is important! Must be before return statement!
return convertView;
}
protected class ViewHolder {
protected TextView title;
protected CheckBox checkBox;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With