I need to access the text in a ListView item through a long click selection. For old Android versions I have successfully done this with context menus with the code below.
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
String text = ((TextView) info.targetView).getText().toString();
switch (item.getItemId()) {
case R.id.getText:
getText(text);
return true;
default:
return super.onContextItemSelected(item);
}
}
For newer Android versions, however, I would like to do this with the Contextual Action Bar but can’t figure out how to extract the selected text after having selected an item in the bar. The below code does not work.
myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
myListView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
String text = ((TextView) info.targetView).getText().toString();
switch (item.getItemId()) {
case R.id.contextDelete:
getText(text);
return true;;
default:
return false;
}
}
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
return true;
}
//Other actionmode methods...
});
The Contextual Action Bar shows up ok, but when picking an item from it I get a NullPointerException at the AdapterContextMenuInfo line, since this was obviously made for context menus and not action bars. Is there some equivalent for this for Action bars perhaps? Or how can I get the ListView item text in this case? Thanks.
getCheckedItemPositions()onListViewwill return the item positions the user has checked, andgetCheckedItemIds()will return their ID values if you are using something likeCursorAdapter.Here is a sample project demonstrating the use of
CHOICE_MODE_MULTIPLE_MODALon API Level 11+ and falling back to context menus on older devices.