Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to find the position clicked from the context menu

I have a list view filled with data. I set up a context menu for the listview using the following code:

list.setOnCreateContextMenuListener (   new View.OnCreateContextMenuListener()    {         public void onCreateContextMenu(ContextMenu menu, View view, ContextMenu.ContextMenuInfo menuInfo)          {        AdapterContextMenuInfo mi =(AdapterContextMenuInfo) menuInfo;        menu.add(0, 0, 0, "Delete item");                     }    } ); 

I have the following method override to control de contextmenu menuitem selected:

@Override public boolean onContextItemSelected(MenuItem item)  {   switch(item.getItemId())    {    case 0:      ShowAlert("hello from delete item");     break;    default:    return super.onContextItemSelected(item);    }    return true;  } 

In this overridden method, how could I find the item of the list view that was clicked?

like image 754
Sosi Avatar asked Mar 16 '10 10:03

Sosi


1 Answers

You can use the ContextMenu.ContextMenuInfo.

Something like that:

@Override public boolean onContextItemSelected(MenuItem item) {     AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();     int index = info.position; } 

You can also get the exact View for which the menu is being displayed:

@Override public boolean onContextItemSelected(MenuItem item) {     AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();     int index = info.position;     View view = info.targetView; } 
like image 52
Dimitar Dimitrov Avatar answered Oct 13 '22 21:10

Dimitar Dimitrov