Actually, it looked uncomfortable because there is no clean and simple solution that I could make Google. HFM (there is a man of faith) and KISS (keep it just stupid) helped;)
1.start in single select mode and install all listeners (this is done where you install the list adapter)
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE); listView.setOnItemLongClickListener(liListener); listView.setMultiChoiceModeListener(mcListener);
2.Use the interfaces to switch between selection modes. TRICK, to make it work, is to return to single-choice mode outside the implementation, that is, AFTER you destroy the action mode! So just use a simple flag to mark the destruction of the CAB. Another TRICK must return false onItemLongClick for the selection mode to take effect.
private OnItemLongClickListener liListener = new OnItemLongClickListener() { @Override public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) { listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL); isCABDestroyed = false; return false; // so this action does not consume the event!!! } }; private MultiChoiceModeListener mcListener = new MultiChoiceModeListener() { @Override public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) { final int checkedCount = listView.getCheckedItemCount(); switch (checkedCount) { case 0: mode.setSubtitle(null); break; case 1: mode.setSubtitle("One item selected"); break; default: mode.setSubtitle("" + checkedCount + " items selected"); break; } } @Override public boolean onActionItemClicked(ActionMode mode, MenuItem item) { switch (item.getItemId()) { case R.id.delete: //do your action command here mode.finish(); return true; default: return false; } } @Override public boolean onCreateActionMode(ActionMode mode, Menu menu) { MenuInflater inflater = mode.getMenuInflater(); inflater.inflate(R.menu.context_menu, menu); return true; } @Override public void onDestroyActionMode(ActionMode mode) { isCABDestroyed = true; // mark readiness to switch back to SINGLE CHOICE after the CABis destroyed } @Override public boolean onPrepareActionMode(ActionMode mode, Menu menu) { return false; } };
3. Here come back
@Override public void onListItemClick(ListView l, View v, int position, long id) { super.onListItemClick(l, v, position, id); if(isCABDestroyed) { listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
Gabriel costea
source share