Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>On the onCreate method call <a href="http://developer.android.com/reference/android/app/Activity.html#registerForContextMenu(android.view.View)" rel="noreferrer">registerForContextMenu</a> like this:</p> <pre><code>registerForContextMenu(getListView()); </code></pre> <p>and then populate the menu on <a href="http://developer.android.com/reference/android/app/Activity.html#onCreateContextMenu(android.view.ContextMenu,%20android.view.View,%20android.view.ContextMenu.ContextMenuInfo)" rel="noreferrer">onCreateContextMenu(ContextMenu menu, View view, ContextMenuInfo menuInfo)</a>. The menuInfo argument can provide information about which item was long-clicked in this way:</p> <pre><code>AdapterView.AdapterContextMenuInfo info; try { info = (AdapterView.AdapterContextMenuInfo) menuInfo; } catch (ClassCastException e) { Log.e(TAG, "bad menuInfo", e); return; } long id = getListAdapter().getItemId(info.position); </code></pre> <p>and you add menu items in the usual way calling <a href="http://developer.android.com/reference/android/view/Menu.html#add(int,%20int,%20int,%20java.lang.CharSequence)" rel="noreferrer">menu.add</a>:</p> <pre><code>menu.add(0, MENU_ITEM_ID, 0, R.string.menu_string); </code></pre> <p>and when the user picks an option, <a href="http://developer.android.com/reference/android/app/Activity.html#onContextItemSelected(android.view.MenuItem)" rel="noreferrer">onContextItemSelected</a> is called. Also <a href="http://developer.android.com/reference/android/app/Activity.html#onMenuItemSelected(int,%20android.view.MenuItem)" rel="noreferrer">onMenuItemSelected</a> and this fact is not explicitly explained in the documentation except to say that you use the other method to receive the calls from the context menu; just be aware, don't share ids.</p> <p>On onContextItemSelected you can get ahold of the MenuInfo and thus the id of the item selected by calling <a href="http://developer.android.com/reference/android/view/MenuItem.html#getMenuInfo()" rel="noreferrer">getMenuInfo()</a>:</p> <pre><code>try { info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo(); } catch (ClassCastException e) { Log.e(TAG, "bad menuInfo", e); return false; } long id = getListAdapter().getItemId(info.position); </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload