How to select/deselect all checkBox?

独自空忆成欢 提交于 2019-12-01 09:00:37
Mohammed Azharuddin Shaikh
boolean flag = true;

Now on your button click swap the value of flag

flag = !flag;
adapter.notifydatasetchanged();

Now in your getView method

public View getView(int position, View convertView, ViewGroup parent) {
    View vi = convertView;
    ViewHolder holder;
    if (convertView == null) {
        vi = inflater.inflate(R.layout.item, null);
        holder = new ViewHolder();
        holder.text = (TextView) vi.findViewById(R.id.text);
        holder.image = (ImageView) vi.findViewById(R.id.image);
        holder.ck = (CheckBox) vi.findViewById(R.id.chkbox);
        vi.setTag(holder);
    } else {
        holder = (ViewHolder) vi.getTag();
    }
    holder.ck.setChecked(flag);
    holder.text.setText(nume[position]);
    holder.image.setTag(data[position]);
    imageLoader.DisplayImage(data[position], activity, holder.image);
    return vi;
}

This will get all the views in your listview and will get the checkbox in each view and sets them to be checked:

List<View> listOfViews = new ArrayList<View>();
listView1.reclaimViews(listOfViews);
for (View v : listOfViews)
{
    CheckBox cb = (CheckBox)v.findViewById(R.id.checkbox);
    cb.setChecked(true);
}

UPDATE:

Before initializing the adapter, create an arraylist that contains the checkstates of all the checkboxes. Then pass this arraylist as an argument to your custom adapter and use in the getView() function (checkStates is the arraylist in the below code):

    public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        ViewHolder holder;
        if(convertView==null){
            vi = inflater.inflate(R.layout.item, null);
            holder=new ViewHolder();
            holder.text=(TextView)vi.findViewById(R.id.text);;
            holder.image=(ImageView)vi.findViewById(R.id.image);
            CheckBox checkbox = (CheckBox)vi.findViewById(R.id.chkbox);
            checkbox.setChecked(checkStates.get(position);
            holder.ck= checkbox;
            vi.setTag(holder);
        }
        else
            holder=(ViewHolder)vi.getTag();

        holder.text.setText(nume[position]);
        holder.image.setTag(data[position]);
        holder.ck.setChecked(checkStates.get(position));
        imageLoader.DisplayImage(data[position], activity, holder.image);
        return vi;
    }

Then when you want to check all the checkboxes, set all the values in the arraylist containing the checkstates of the checkboxes as true. Then call listView1.setAdapter(adapter);

I asigned an id to each selected item and then use a HashMap to keep track of the selected items

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!