How do I properly initiate a multi-select Contextual Action Bar for ListFragment (having issues)
W

1

6

I have a ListFragment associated with a simple ArrayAdapter. The ListView holds a list of checkable items and its XML layout is as follows:

<ListView android:id="@id/android:list"
              android:layout_width="match_parent"
              android:layout_height="0dip"
              android:layout_weight="1"
              android:layout_marginLeft="2mm"
              android:layout_marginRight="2mm"
              android:drawSelectorOnTop="false"
              android:longClickable="true"
              android:choiceMode="multipleChoiceModal"/>

As you can see, I have set the long-clickable and choicemode attributes in the XML layout.

I set the appropriate listeners in the ListFragment's onViewCreated callback:

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    ListView list_view = getListView();
    list_view.setMultiChoiceModeListener(this);
    list_view.setOnItemLongClickListener(this);
}

I pass in this as the listener parameter because my ListFragment has also implemented the callbacks of those listeners.

This is the callback I am having issues with:

@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id
{
    activity.startActionMode(this);
    return true;
}

Firstly, that onItemLongClick is never called. But, the Contextual Action Bar (CAB) starts and works perfectly when a list item is long-clicked!

In fact, the CAB initiates properly without this callback! My callback uses activity.startActionMode(this), which would show the CAB, but does not facilitate checking off items in the list (I tested this elsewhere).

How do I properly programmatically handle long clicks to initiate the CAB and facilitate checking list items?

I am using the methods presented in the Android Developer Guide topics (they used onLongClickListener, which I have also tried to no avail), but it does not seem to be working.

Weaverbird answered 4/3, 2013 at 8:2 Comment(0)
O
1

I'm guessing you figured this one out, but for posterity, what you need to do to add the context menu is simply to add the context menu items in onContextMenuCreated, under your root activity/fragment:

@Override
public void onCreateContextMenu(ContextMenu menu, View v,
    ContextMenuInfo menuInfo) {
  if (v.getId()==R.id.list) {
    String[] menuItems = getResources().getStringArray(R.array.menu);
    for (int i = 0; i<menuItems.length; i++) {
      menu.add(Menu.NONE, i, i, menuItems[i]);
    }
  }
}

Then, respond to context menu clicks under onContextMenuCreated. You can read more here:

http://www.mikeplate.com/2010/01/21/show-a-context-menu-for-long-clicks-in-an-android-listview/

Onestep answered 26/7, 2013 at 12:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.