I have a ListView that will allow the user to long-press an item to get a context menu. The problem I\'m having is in determining which ListItem
they long-press
First of all, I'm wondering if you're making things a little overly complicated by using View.setOnCreateContextMenuListener()
. Things get a lot easier if you use Activity.registerForContextMenu()
, because then you can just use Activity.onCreateContextMenu()
and Activity.onContextItemSelected()
to handle all of your menu events. It basically means you don't have to define all these anonymous inner classes to handle every event; you just need to override a few Activity methods to handle these context menu events.
Second, there's definitely easier ways to retrieve the currently selected item. All you need to do is keep a reference either to the ListView
or to the Adapter
used to populate it. You can use the ContextMenuInfo as an AdapterContextMenuInfo to get the position of the item; and then you can either use ListView.getItemAtPosition()
or Adapter.getItem()
to retrieve the Object
specifically linked to what was clicked. For example, supposing I'm using Activity.onCreateContextMenu()
, I could do this:
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
// Get the info on which item was selected
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
// Get the Adapter behind your ListView (this assumes you're using
// a ListActivity; if you're not, you'll have to store the Adapter yourself
// in some way that can be accessed here.)
Adapter adapter = getListAdapter();
// Retrieve the item that was clicked on
Object item = adapter.getItem(info.position);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
// Here's how you can get the correct item in onContextItemSelected()
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
Object item = getListAdapter().getItem(info.position);
}