2

I am creating an application to send contacts. I displayed the contact details in a listview populated by using custom adapter with name number and a checkbox. The problem is when i check a checkbox random check boxes are also get selected in the list. I refered so many questions here and stil its not working

the method for populating list in the adapter class is

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ContactsBean contact = contacts.get(position);
    ViewHolder holder = null;
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) mainActivity
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        convertView = inflater.inflate(R.layout.list_layout, null);
        holder = new ViewHolder();
        holder.number = (TextView) convertView.findViewById(R.id.numberTextView);
        holder.name = (TextView) convertView.findViewById(R.id.nameTextView);
        holder.box = (CheckBox) convertView.findViewById(R.id.checkBox);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    holder.name.setText(contact.getName());
    holder.number.setText(contact.getNumber().get(0));
    holder.name.setTag(contact);
    holder.box.setTag(contact);
    holder.box.setOnClickListener(this);
    holder.box.setSelected(contact.isSelect());
    return convertView;
}

@Override
public void onClick(View v) {
    if (v.getId() == R.id.checkBox) {
        ContactsBean bean = (ContactsBean) v.getTag();
        bean.setSelect(!bean.isSelect());
        notifyDataSetChanged();
    }
}

private static class ViewHolder {
    public TextView number;
    public TextView name;
    public CheckBox box;
}
suhail c
  • 1,169
  • 2
  • 16
  • 40
  • here is my view [enter link description here](http://stackoverflow.com/questions/6470089/why-did-the-listview-repeated-every-6th-item/41900575#41900575) – Samir Jan 27 '17 at 18:23

1 Answers1

0

You should be calling holder.box.setChecked(contact.isSelect()); instead of setSelected() to properly reset whether or not the CheckBox is checked.

The selected state does not impact whether or not the box is checked.

Bryan Herbst
  • 66,602
  • 10
  • 133
  • 120