how can I access all the checkboxes in my listview from the onclick event of a given checkbox. What I want to achieve is to disable all unckecked checkboxes when the number of checked checkboxes in greater than a given number.
Thanks you!
public class FriendAdapter extends SimpleCursorAdapter implements OnClickListener {
private Context mContext;
private int mLayout;
private Cursor mCursor;
private int mNameIndex;
private int mIdIndex;
private LayoutInflater mLayoutInflater;
private final ImageDownloader imageDownloader = new ImageDownloader();
private final class ViewHolder {
public TextView name;
public ImageView image;
public CheckBox checkBox;
}
public FriendAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.mContext = context;
this.mLayout = layout;
this.mCursor = c;
this.mNameIndex = mCursor.getColumnIndex(WhipemDBAdapter.KEY_NAME);
this.mIdIndex = mCursor.getColumnIndex(WhipemDBAdapter.KEY_FB_ID);
this.mLayoutInflater = LayoutInflater.from(context);
}
public View getView(int position, View convertView, ViewGroup parent) {
if (mCursor.moveToPosition(position)) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = mLayoutInflater.inflate(mLayout, null);
viewHolder = new ViewHolder();
viewHolder.name = (TextView) convertView.findViewById(R.id.contact_name);
viewHolder.image = (ImageView) convertView.findViewById(R.id.contact_pic);
viewHolder.checkBox = (CheckBox) convertView.findViewById(R.id.checkbox);
viewHolder.checkBox.setOnClickListener(this);
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) convertView.getTag();
}
String name = mCursor.getString(mNameIndex);
String fb_id = mCursor.getString(mIdIndex);
boolean isChecked = ((GlobalVars) mContext.getApplicationContext()).isFriendSelected(fb_id);
viewHolder.name.setText(name);
imageDownloader.download("http://graph.facebook.com/"+fb_id+"/picture", viewHolder.image);
viewHolder.checkBox.setTag(fb_id);
viewHolder.checkBox.setChecked(isChecked);
}
return convertView;
}
@Override
public void onClick(View v) {
CheckBox cBox = (CheckBox) v;
String fb_id = (String) cBox.getTag();
/*
How can I access all the checkboxes here?
*/
if (cBox.isChecked()) {
if (!((GlobalVars) mContext.getApplicationContext()).isFriendSelected(fb_id))
((GlobalVars) mContext.getApplicationContext()).addSelectedFriend(fb_id);
} else {
if (((GlobalVars) mContext.getApplicationContext()).isFriendSelected(fb_id))
((GlobalVars) mContext.getApplicationContext()).removeSelectedFriend(fb_id);
}
}
}
First of all use onCheckChangedListener instead of
onClickListener. Keep a global counter for the number of friends checked, and set its value in the constructor itself. Next in theonCheckedChangedmethod increment or decrement the counter based on whether the checkbox has been checked or not. If the counter becomes more than your count then invalidate the listview and in the getview method set the checkbox’s visibility as invisible (or gone)