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(R.id.cb); cb.setChecked(val); } editor.apply(); } 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; } @Override 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(R.id.cb); holder.s = item; item.checked = prefs.getBoolean("PF_"+item.getID(),true); //holder.cb.setTag(holder); holder.cb.setTag(item); holder.cb.setChecked(item.checked); holder.cb.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton v, boolean isChecked) { Station s = (Station) v.getTag(); editor.putBoolean("PF_"+s.getID(), isChecked); editor.apply(); } }); v.setTag(holder); } else { holder = (StationCBViewHolder) v.getTag(); } holder.cb.setText(item.toString()); holder.cb.setChecked(item.checked); return v; } }
Full code here: http://pastebin.com/8NMbHqRV
The code still has some bugs related to SharedPreferences and SharedPreferences.Editor, but at least it checks and unchecks all checkboxes.
No comments:
Post a Comment