Naruto
Naruto

Reputation: 9634

Android Select multiple items in listview

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);
            }

Upvotes: 0

Views: 823

Answers (1)

Akshay Sharma
Akshay Sharma

Reputation: 418

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 { /* ... */ }

Upvotes: 1

Related Questions