views:

2543

answers:

5

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-pressed. I've tried doing this:

myListView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
  @Override public void onCreateContextMenu(ContextMenu menu, final View v, ContextMenuInfo menuInfo) {
   menu.add("Make Toast")
    .setOnMenuItemClickListener(new OnMenuItemClickListener() {
     @Override public boolean onMenuItemClick(MenuItem item) {
      String toastText = "You clicked position " + ((ListView)v).getSelectedItemPosition();
      Toast.makeText(DisplayScheduleActivity.this, toastText, Toast.LENGTH_SHORT).show();
      return true;
     }
    });
  } 
 });

but it just hangs until an ANR pops up. I suspect that after the menu is created the ListItem is no longer selected.

It looks like you could monitor for clicks or long-clicks then record the clicked item there:

 mArrivalsList.setOnItemLongClickListener(new OnItemLongClickListener() {
  @Override public boolean onItemLongClick(AdapterView<?> parent, View v, int position, long id) {
   // record position/id/whatever here
   return false;
  }
 });

but that feels majorly kludgey to me. Does anyone have any better solutions for this?

A: 

Isn't the view argument the actual selected row's view, or am I missing the question here?

ListView lv;
private OnItemLongClickListener onLongClick = new OnItemLongClickListener() {
    public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
            int arg2, long arg3) {
        lv.showContextMenuForChild(arg1);
        lv.showContextMenu();
        return false;
    }
};
sadboy
The view argument is the ListView.
fiXedd
+1  A: 

We have used with success:

@Override
public boolean onContextItemSelected
(
MenuItem item
)
    {
    if (!AdapterView.AdapterContextMenuInfo.class.isInstance (item.getMenuInfo ()))
        return false;

    AdapterView.AdapterContextMenuInfo cmi =
        (AdapterView.AdapterContextMenuInfo) item.getMenuInfo ();

    Object o = getListView ().getItemAtPosition (cmi.position);

    return true;
    }
Nate
+8  A: 

I do exactly this. In my onCreateContextMenu(...) method, I cast the ContextMenu.ContextMenuInfo to AdapterView.AdapterContextMenuInfo. From there, you can get the targetView, which you cast again to the widget. The complete code is available in HomeActivity.java, look for the onCreateContextMenu(...) method.

@Override
public void onCreateContextMenu(ContextMenu contextMenu,
                                View v,
                                ContextMenu.ContextMenuInfo menuInfo) {
    AdapterView.AdapterContextMenuInfo info =
            (AdapterView.AdapterContextMenuInfo) menuInfo;
    selectedWord = ((TextView) info.targetView).getText().toString();
    selectedWordId = info.id;

    contextMenu.setHeaderTitle(selectedWord);
    contextMenu.add(0, CONTEXT_MENU_EDIT_ITEM, 0, R.string.edit);
    contextMenu.add(0, CONTEXT_MENU_DELETE_ITEM, 1, R.string.delete);
}

Note that I store the selected text as well as the select id in private fields. Since the UI is thread confined, I know the selectedWord and selectedWordId fields will be correct for later actions.

Eric Burke
This is how I've done it also. The key was figuring out that the ContextMenuInfo object was an instance of AdapterContextMenuInfo. Took me a while to figure that out.
mbaird
This will only work if the actual data behind the item is closely tied to the View created from the Adapter. I've found this is often not the case with more complicated Adapters I've created (for example, it'll display an image and a name; clicking on it will open more details about the item, based on more data stored in the Adapter).
Daniel Lew
+7  A: 

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);
}
Daniel Lew
A: 

and don't forget to put this

registerForContextMenu(listview);

in your onCreate method to get your context Menu visible.

sami boussacsou