Get selected item in a ListItem ContextMenu

Jeshurun picture Jeshurun · Jun 24, 2012 · Viewed 8.8k times · Source

I have a ListView which creates a ContextMenu on long press of one of its elements. How do I find the element that was selected in the ListView that created this context menu (not the selected MenuItem)? Here is my code:

list.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
    @Override
    public void onCreateContextMenu(ContextMenu menu, final View v,
            ContextMenuInfo menuInfo) {
        menu.setHeaderTitle("Actions");
        android.view.MenuItem remove = menu.add("Remove");
        final int selectedItem = ((ListView)v).getSelectedItemPosition();
        remove.setOnMenuItemClickListener(new OnMenuItemClickListener() {   
            @Override
            public boolean onMenuItemClick(android.view.MenuItem item) {
                doSomething(listAdapter.getItem(selectedItem)); // NPE here
                return true;
            }
        });
    }
});

Please note that I do not want the item that was selected from the context menu, but the ListView item that triggered this context menu instead.

Answer

Vipul picture Vipul · Jun 24, 2012

You will need AdapterContextMenuInfo for it.

Following Snippet will help you

public boolean onContextItemSelected(MenuItem item) {
      AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
      String[] names = getResources().getStringArray(R.array.names);
      switch(item.getItemId()) {
      case R.id.edit:
            Toast.makeText(this, "You have chosen the " + getResources().getString(R.string.edit) +
                        " context menu option for " + names[(int)info.id],
                        Toast.LENGTH_SHORT).show();
            return true;
      …………………..
      default:
            return super.onContextItemSelected(item);
      }