0

I'm trying to implement multiple list item selection and user can perform actions based on menu item appears on actionbar.

I have tried a way ListView.CHOICE_MODE_MULTIPLE_MODAL but this option works only for API 11 or above.

Is there a way we can make use of the same technique for API 11 below i.e below code works only API 11 onwards.

list.setMultiChoiceModeListener(new MultiChoiceModeListener() {

            @Override
            public void onItemCheckedStateChanged(ActionMode mode,
                    int position, long id, boolean checked) {
                // Capture total checked items
                final int checkedCount = list.getCheckedItemCount();
                // Set the CAB title according to total checked items
                mode.setTitle(checkedCount + " Selected");
                // Calls toggleSelection method from ListViewAdapter Class
                listviewadapter.toggleSelection(position);
            }
Naruto
  • 9,476
  • 37
  • 118
  • 201

1 Answers1

1

Using ActionBarSherlock the MultiChoiceModeListener if you want to support API level < 11.

A workaround is to use the onItemClickListener.

List setup:

listView = (ListView) timeline.findViewById(android.R.id.list);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setItemsCanFocus(false);
listView.setAdapter(new ListAdapter(getActivity(), R.layout.cleaning_list_item, items));

Listener of ListFragment or ListActivity:

@Override
  public void onListItemClick(ListView l, View v, int position, long id) {
SparseBooleanArray checked = listView.getCheckedItemPositions();
boolean hasCheckedElement = false;
for (int i = 0; i < checked.size() && !hasCheckedElement; i++) {
    hasCheckedElement = checked.valueAt(i);
}

if (hasCheckedElement) {
    if (mMode == null) {
        mMode = ((SherlockFragmentActivity) getActivity()).startActionMode(new MyActionMode());
        mMode.invalidate();
    } else {
        mMode.invalidate();
    }
} else {
    if (mMode != null) {
        mMode.finish();
    }
}
}

Where MyActionMode is an implementation of ActionMode.Callback:

private final class MyActionMode implements ActionMode.Callback { /* ... */ }
Akshay Sharma
  • 418
  • 3
  • 12
  • Hi, i tried your technique, in mine selection is not getting retained but i'm able to see the actionbar with context menu. how to retain blue color selection on a item?. thanks for your help – Naruto Jun 22 '14 at 09:44
  • just go to the link u will understand everything ...http://stackoverflow.com/questions/14737519/how-can-you-implement-multi-selection-and-contextual-actionmode-in-actionbarsher/14737520#14737520 – Akshay Sharma Jun 22 '14 at 09:50
  • if u find it useful dont forget to tick..:P – Akshay Sharma Jun 22 '14 at 09:51