jeudi 3 septembre 2015

Android listview multiple items are checked while selecting a checkbox

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;
}




Aucun commentaire:

Enregistrer un commentaire