Get selected item in ListItem ContextMenu

I have a ListView that creates ContextMenu when a long click of one of its elements. How to find the item that was selected in the ListView that created this context menu (and 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 to be selected from the context menu, but the ListView element that called this context menu.

+4
source share
1 answer

You will need AdapterContextMenuInfo .

The 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); } 
+8
source

All Articles