Search code examples
androidlistviewandroid-arrayadapter

Toggle checkbox programmatically


I have a ListView of items that need to be checkable/uncheckable. I have set up an ArrayAdapter that is currently using android.R.layout.simple_list_item_multiple_choice as the row, and everything displays just fine. I am also able to properly get the clicks on this item. However, the Checkbox in the UI does not toggle when the item is selected. I've been trying to figure this out for a while, can anyone point me in the right direction? I just want to know how to force the UI to update to reflect the changed state of the checkbox.

I can provide code if needed, but I'm trying to look for something very specific here, so I figure posting a bunch of my code wouldn't be of much help.

Thanks!


Solution

  • First of all go through my this answer: Android listview with check boxes?

    Nice as you want to implement checked/unchecked check boxes in ListView, you just need to implement below lines in getView() method:

     // also check this lines in the above example
    ViewHolder holder = (ViewHolder) view.getTag();
    holder.checkbox.setChecked(list.get(position).isSelected());
    

    Also check the getView() method for the implementation of event on CheckBox residing inside the ListView:

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View view = null;
        if (convertView == null) {
            LayoutInflater inflator = context.getLayoutInflater();
            view = inflator.inflate(R.layout.rowbuttonlayout, null);
            final ViewHolder viewHolder = new ViewHolder();
            viewHolder.text = (TextView) view.findViewById(R.id.label);
            viewHolder.checkbox = (CheckBox) view.findViewById(R.id.check);
            viewHolder.checkbox
                .setOnCheckedChangeListener(
                    new CompoundButton.OnCheckedChangeListener() {
    
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView,
                            boolean isChecked) {
                        Model element = (Model) viewHolder.checkbox
                                .getTag();
                        element.setSelected(buttonView.isChecked());
                    }
                });
            view.setTag(viewHolder);
            viewHolder.checkbox.setTag(list.get(position));
        } else {
            view = convertView;
            ((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
        }
        ViewHolder holder = (ViewHolder) view.getTag();
        holder.text.setText(list.get(position).getName());
        holder.checkbox.setChecked(list.get(position).isSelected());
        // ......  
    }