Clear all selected items in a gridview

1.2k Views Asked by At

I have a gridview inside a ExpandableListView with CHOICE_MODE_MULTIPLE, I'm trying to deselect all items when I press a button, but the way I'm doing it it is only unselecting the last item, how can I clear all of them?

@Override
public int getCount() {
    return child.size();
}

@Override
public Object getItem(int position) {
    return position;
}

@Override
public long getItemId(int arg0) {
    return 0;
}

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    holder = null;
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) mContext
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.child_item, null);
        holder = new ViewHolder();

        holder.text = (TextView) convertView.findViewById(R.id.name);
        convertView.setTag(holder);
        final View finalConvertView = convertView;
        convertView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isChecked = child.get(position).isChecked();
                if (!isChecked) {
                    child.get(position).setChecked(true);
                } else {
                    child.get(position).setChecked(false);                       
                }

                ex.findViewById(R.id.notificar).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(final View v) {
                        //clear all selected items
                        for(int i = 0; i< getCount(); i++){
                            child.get(i).setChecked(false);
                        }
                    }
                });
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            holder.text.setText(child.get(position).getNome());
            return convertView;
        }
    }
}
static class ViewHolder {
    TextView text;
}
2

There are 2 best solutions below

2
On BEST ANSWER

Try calling listView.clearChoices(); and adapter.notifyDataSetChanged(); from the activity or fragment containing the list, not inside the adapter.

0
On

Your problem is using calling child.size first, it is returning 1.
You are getting the child count from a different view.

@Override
public int getCount() {
    return child.size();
}

If you call child.size() within you OnClickListener where you are using the

public void onClick(final View v) {

You should be iterating through the array adapter of the list, as the child.counts of the view will be different from the number of checked list items, if the list is scrollable. As there will be less items in the view (they are recycled) than within the list.