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.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With