I have a list view which has been registered for a context menu. For some items within the list a context menu is not applicable. In these cases I just don’t inflate a menu in the onCreateContextMenu method.
Unfortunately this means that when items that don’t display a context menu are long-clicked Android then handles this as a short-click (presumably because the context menu would normally return true to say that the long-click event has been handled).
This results in an inconsistent behaviour in the listview – some items show a context menu when you long click them – others don’t and then perform the default click behaviour. How can I ensure that even items that don’t display a context menu consume the long click so that the onItemClick method isn’t called?
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
Playable playable = (Playable) info.targetView.getTag(R.id.playable);
if (playable != null && !(playable instanceof AutoRadioStation) && !(playable.getId().equals(Playlist.AUTOMATIC_PLAYLIST))) {
v.setTag(R.id.playable, playable); // This copies the tag so that it is contained within the view used for the menu.
Drawable stationImage = (Drawable) ((ImageView) info.targetView.findViewById(R.id.artwork)).getDrawable().getConstantState().newDrawable();
menu.setHeaderTitle(playable.getName());
menu.setHeaderIcon(stationImage);
MenuInflater inflater = getActivity().getMenuInflater();
inflater.inflate(R.menu.saved_context_menu, menu);
}
}
I finally got around to implementing a version of NathanZ solution. There didn’t seem to be much stuff out there about turning a contextMenu into a DialogFragment so I’ll paste most of my solution here.
Implementing an onLongItemClick listener also meant that I was able to have a long-click event that didn’t require a menu within the listview. Unfortunately because you can’t pass menus around to a dialog I had to reuse an existing ListViewElement type to store an id and a text string for each “menu” item in my listview.