How to get the position of an element clicked on ContextMenu?

I use this code to get the Clicked Item position in the context menu:

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

as suggested here:

Android: how to find the position pressed from the context menu

But I get a NullPointerException in the line:

  int index = info.position; 

why is that so?

EDIT

I have 2 registered views for the Menu context like this:

 button1.onClick(view v){ registerForContextMenu(v); openContextMenu(v); } button2.onClick(view v){ registerForContextMenu(v); openContextMenu(v); } 

then depending on v.getId () I started the menu.

+4
source share
2 answers

You can use directly:

BEGINNING OF WORK

 @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { AdapterView.AdapterContextMenuInfo info; try { info = (AdapterView.AdapterContextMenuInfo) menuInfo; } catch (ClassCastException e) { // If the menu object can't be cast, logs an error. Log.e("MENU", "bad menuInfo", e); return; } position = sectionAdapter.getIndexForPosition(info.position); menu.setHeaderTitle(""); String[] menuItems = { "item1","item2","item3","item4" }; for (int i = 0; i < menuItems.length; i++) { menu.add(Menu.NONE, i, i, menuItems[i]); } } 

EDITED END

 public boolean onContextItemSelected(MenuItem item) { // TODO Auto-generated method stub int position = item.getItemId(); switch (position) { case 0: break; . . . default: break; } } 

Hope this helps you.

0
source

Source: https://habr.com/ru/post/1434191/


All Articles