I want to limit checkbox
selection in android listivew
to for example only 2 checkboxes should be selected when user selected 3 position chackbox position one checkboc was unchecked.
User can select any two checkboxes from the list, how to achieve this? Here is my gist file:
public class ListAdapter extends ArrayAdapter<ListModel> {
private ListModel listModel;
private int selectedItemCounter = 0;
public ListAdapter(Context context, List<ListModel> listModels) {
super(context, 0, listModels);
}
@NonNull
@Override
public View getView(final int position, View convertView, @NonNull ViewGroup parent) {
listModel = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_view_item_row, parent, false);
}
TextView productTitle = (TextView) convertView.findViewById(R.id.product_title);
TextView productDescription = (TextView) convertView.findViewById(R.id.product_description);
final CheckBox icon_right = (CheckBox) convertView.findViewById(R.id.icon_right);
LinearLayout Listener = (LinearLayout) convertView.findViewById(R.id.list_view_listener);
Listener.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
icon_right.performClick();
}
});
icon_right.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
selectedItemCounter++;
} else {
selectedItemCounter--;
}
if (selectedItemCounter >= 3) {
buttonView.setChecked(false);
selectedItemCounter--;
notifyDataSetChanged();
}
}
});
icon_right.setChecked(false);
productTitle.setText(listModel.product);
productDescription.setText(listModel.productDetails);
// icon_right.setImageResource(R.drawable.icon_save);
return convertView;
}
}
Try this:
Hope that help!