friend 们,
我想将 android listivew 中的复选框选择限制为例如只应选择 3 个复选框,否则它应该给出错误消息。
用户可以从列表中选择任意三个复选框
任何人指导我如何实现这一目标?这是我的适配器
public class AdapterContacts extends BaseAdapter {
private LayoutInflater mInflater;
public Context context;
public static List<myContacts> contacts;
public AdapterContacts(Context context,List<myContacts> list) {
mInflater = LayoutInflater.from(context);
this.context = context;
contacts= list;
}
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_contacts, null);
holder = new ViewHolder();
holder.contactName = (TextView) convertView.findViewById(R.id.contactName);
holder.contactNumber = (TextView) convertView.findViewById(R.id.contactNumber);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
myContacts contact = getItem(position);
holder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton checkboxView, boolean isChecked) {
myContacts c = (myContacts) checkboxView.getTag();
c.setSelected(isChecked);
// to put that check of selection limit with error
}
});
holder.checkBox.setTag(contact);
holder.checkBox.setChecked(contact.isSelected());
holder.contactName.setText(contact.getContactName());
holder.contactNumber.setText(contact.getPhoneNumber());
return convertView;
}
@Override
public int getCount() {
return contacts.size();
}
@Override
public myContacts getItem(int position) {
return contacts.get(position);
}
@Override
public long getItemId(int arg0) {
return 0;
}
class ViewHolder {
TextView contactName;
TextView contactNumber;
CheckBox checkBox;
}
}
任何帮助,将不胜感激。
最佳答案
最后我解决了这个问题:) 其中 globalInc 是具有默认值 0 的全局变量
holder.checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
@Override
public void onCheckedChanged(CompoundButton checkboxView, boolean isChecked)
{
myContacts c = (myContacts) checkboxView.getTag();
if(isChecked)
{
globalInc++;
}
else if(!isChecked)
{
globalInc--;
}
if(globalInc >= 4)// it will allow 3 checkboxes only
{
Toast.makeText(context, "Error = " + globalInc, Toast.LENGTH_LONG).show();
checkboxView.setChecked(false);
globalInc--;
}
else
{
c.setSelected(isChecked);
}
System.out.println(" --------------- "+globalInc);
}
});