Nov 18, 2011

Android : Checkbox ListView - (un) check all

This recycling of views in android is pretty insane. Pain to work with.

So the problem is how to check all check boxes in a list view, if a list view only contains the visible items.

Iterating through the adapter or array of holders was pretty unreliable, some checkboxes weren't affected.

What I did was actually add an attribute to the data object and iterate through this object array (the same way it get's added in the adapter)-

Here are some functions:
 public void toggleCheck(Boolean val) {
  for(Station s : stations.list) {
   s.checked = val;
   editor.putBoolean("PF_"+s.getID(), val);
  for(int i=0 ; i < lv.getChildCount() ; i++) {
   CheckBox cb = (CheckBox) lv.getChildAt(i).findViewById(;

    private class StationCBViewHolder {
        public CheckBox cb;
        public Station s;
 private class StationListAdapter extends ArrayAdapter {
     private ArrayList items;
     private Context context;
     public StationListAdapter(Context context, int tvResId, ArrayList items) {
         super(context, tvResId, items);
         this.items = items;
         this.context = context;

     public View getView(int pos, View v, ViewGroup parent) {
      final StationCBViewHolder holder;
      final Station item = items.get(pos);
         if (v == null) {
             LayoutInflater vi = ((Activity)context).getLayoutInflater();
             v = vi.inflate(R.layout.stationcheckboxitem, parent, false);
             holder = new StationCBViewHolder();
             holder.cb = (CheckBox) v.findViewById(;
             holder.s = item;
             item.checked = prefs.getBoolean("PF_"+item.getID(),true);
             holder.cb.setOnCheckedChangeListener(new OnCheckedChangeListener() {
     public void onCheckedChanged(CompoundButton v, boolean isChecked) {
      Station s = (Station) v.getTag();
      editor.putBoolean("PF_"+s.getID(), isChecked);
         } else {
          holder = (StationCBViewHolder) v.getTag(); 


         return v;


Full code here:

The code still has some bugs related to SharedPreferences and SharedPreferences.Editor, but at least it checks and unchecks all checkboxes.

No comments: