This is the first time I’m developing an Android application so this question might be a no-brainer.
I want to limit the number of checkboxes selected (i.e., the user should only be able to select a amximum of 2 checkboxes). How do I do this in onCheckedChanged()?
package com.mainak.walkbuddy;
import java.util.List;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
public class InteractiveArrayAdapter extends ArrayAdapter<Model>
{
private final List<Model> list;
private final Activity context;
public InteractiveArrayAdapter(Activity context, List<Model> list)
{
super(context, R.layout.activity_show_content, list);
this.context = context;
this.list = list;
}
static class ViewHolder
{
protected TextView text;
protected CheckBox checkbox;
}
@Override
public View getView(int position, View convertView, ViewGroup parent)
{
View view = null;
int checkBoxCounter = 0;
int checkBoxInitialized = 0;
if (convertView == null)
{
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.activity_show_content, 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());
return view;
}
}
Add an int counter representing the number of checked items, every time an Item is being checked you check if the counter is not bigger than 2.
If it is bigger than 2 then don’t do anything(don’t set the flag to checked), otherwise just change the flag and increment the counter.
And you should set onClickListener to the view and there change the checked flag to checked/unchecked, and then just call notifydatasetchanged() to change the checked state.
Because there might be some issues keeping the checked state when adding onCheckedChangedListener.