KickingLettuce KickingLettuce - 3 years ago 84
Android Question

Get Position of ContextMenu Selected in RecycleView

Normally for

, I would do this when I wanted to get the position that the user clicked on a Context Menu.

public boolean onContextItemSelected(android.view.MenuItem item) {

AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
position = info.position;

However, ever since I switched to a
, I now get a null pointer here.

The code above is in my main
) while
is done in the
as per the new way.

is also done in the adapter (specifically the constructor).

Answer Source

There're 3 options:

  1. You can pass getAdapterPosition() instead of MenuItem's order

    private class ChipViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
        public ChipViewHolder(View itemView) {
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
            menu.setHeaderTitle("Select The Action");
            menu.add(0, ACTION_1_ID, getAdapterPosition(), "action 1");
            menu.add(0, ACTION_2_ID, getAdapterPosition(), "action 2");

    And then, in Activity listen to onContextItemSelected() and retrieve position by getOrder()

    public boolean onContextItemSelected(MenuItem item) {
        int clickedItemPosition = item.getOrder();
        // do something!
        return super.onContextItemSelected(item);
  2. Use custom implementations of RecyclerView like Teovald/ContextMenuRecyclerView one

  3. Setting MenuItem's clickListener (see ) and handles it there.

Yes, it's very inconvenient API. You can choose the one you like most.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download