Normally for
ListViews
public boolean onContextItemSelected(android.view.MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
position = info.position;
RecycleView
Activity
Fragment
onCreateContextMenu()
adapter
ItemView.setOnCreateContextMenuListener(this);
There're 3 options:
You can pass getAdapterPosition()
instead of MenuItem
's order
private class ChipViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
public ChipViewHolder(View itemView) {
super(itemView);
itemView.setOnCreateContextMenuListener(this);
}
@Override
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()
@Override
public boolean onContextItemSelected(MenuItem item) {
int clickedItemPosition = item.getOrder();
// do something!
return super.onContextItemSelected(item);
}
Use custom implementations of RecyclerView like Teovald/ContextMenuRecyclerView one
Setting MenuItem
's clickListener (see https://stackoverflow.com/a/33179957/1658267 ) and handles it there.
Yes, it's very inconvenient API. You can choose the one you like most.