Using a RecylcerView
, I'm trying to have a popup menu for each item in the list, similar to this:
Creating the popup menu is simple, but how do you get the position of the item clicked in onMenuItemClicked
?
public class Activity extends AppCompatActivity implements PopupMenu.OnMenuItemClickListener {
public void showPopupMenu(View v) {
PopupMenu popupMenu = new PopupMenu(this, v);
MenuInflater inflater = popupMenu.getMenuInflater();
inflater.inflate(R.menu.edit_delete_menu, popupMenu.getMenu());
popupMenu.show();
}
@Override
public boolean onMenuItemClick(MenuItem item) {
//get position here from RecyclerView here?
switch (item.getItemId()) {
case R.id.edit:
//Do position specific action
break;
case R.id.delete:
//Do position specific action
break;
}
return false;
}
}
Alright, so I (surprisingly) managed to answer my own question here.
In order to obtain the position from a
RecylcerView
adapter withinonMenuItemClicked
usingPopupMenu
, I created a custom implementation ofPopupMenu
.Doing so provides much greater flexibility when using
PopupMenu
, such as displaying icons in your menus.Look at Google's source code for
PopupMenu
, and create your own, something likeMyPopupMenu
that is exactly the same, but you can modify certain instances of what the class can do.To complete my problem, I added an
OnClickListener
to the More button within myRecyclerView.Adapter
. When clicked, the button calls an interface method that passes both the button view, and the adapter's current position.In the custom implementation of
MyPopupMenu
, add the variable requirements for each constructor for an int value. Also addint position
to the interface methodonMenuItemClick(MenuItem item, int position)
withinMyPopupMenu
.Finally, assemble in the activity class.
Let me know what you guys think!