Set limit in multi-section ListView mode

I have an ArrayList of strings defined with names, and I add to my ListView object as follows:

I create an Array Adapter and set to multiple selection in both the array and the ListView. This works great, I can scroll and select multiple objects. But the problem is that I want to force the user to be able to select only 4 items from the list. How to set a limit?

adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_multiple_choice,names); nameList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); nameList.setAdapter(adapter); 
+3
source share
2 answers

You can create a List , and whenever the List exceeds a certain size, you can uncheck the first checkbox in the List and remove it from the List , and then add a new one or even deselect another.

So, just register onClick that the size of the list then determines whether you want to handle this extra element.

0
source

Try the following:

 public class AccountListAdapter extends BaseAdapter { @SuppressWarnings("unused") private final static String TAG = AccountListAdapter.class.getSimpleName(); private Context context; private List<Account> rowItems; private int selectedItemCounter = 0; private final int limit; public AccountListAdapter(Context context, List<Account> items, int limit) { this.context = context; this.rowItems = items; this.limit = limit; } public View getView(final int position, View convertView, ViewGroup parent) { LayoutInflater mInflater = (LayoutInflater) context .getSystemService(Activity.LAYOUT_INFLATER_SERVICE); final Account rowItem = (Account) getItem(position); convertView = mInflater.inflate(R.layout.account_selection_item, null); TextView tv = (TextView) convertView.findViewById(R.id.textView); ToggleButton tb = (ToggleButton) convertView .findViewById(R.id.toggleButton); tb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked && !rowItem.isSelected()) { if (selectedItemCounter >= limit) { Toast.makeText(context, "can't be more" + selectedItemCounter, Toast.LENGTH_SHORT).show(); buttonView.setChecked(false); return; } rowItem.setSelected(true); selectedItemCounter++; } else if (!isChecked && rowItem.isSelected()) { rowItem.setSelected(false); selectedItemCounter--; } } }); tv.setText(rowItem.getDevId()); tb.setChecked(rowItem.isSelected()); return convertView; } @Override public int getCount() { return rowItems.size(); } @Override public Object getItem(int position) { return rowItems.get(position); } @Override public long getItemId(int position) { return rowItems.indexOf(getItem(position)); } } 

tried to improve my code using ViewHolder template but failed. if anyone has a better idea please let me know.

0
source

All Articles