user3650602 user3650602 - 2 years ago 190
Android Question

Android onMenuItemClick() - detect which menu clicked?

I'm currently writing a simple application that uses 2 buttons anchored with Pop Up Menus that will display when the button is pressed. That was simple enough, however i'm having trouble with onMenuItemClick() method, which I want to use to change the text of the button to the menu item that was clicked.

Since I have two Pop Up Menus, each with 3 items, does this mean I would have to write 6 different if statements in the onMenuItemClick(), each one attempting to detect which item from which menu was clicked? Or is there a more simple way of doing this, for example specifying 2 onMenuItemClick() methods, each linked to the separate 2 menus?

public class MainActivity extends AppCompatActivity implements OnMenuItemClickListener {

protected void onCreate(Bundle savedInstanceState) {

public void showColourPopUpMenu(View v){
PopupMenu coloursPopUpMenu = new PopupMenu(this, v);

public void showShapePopUpMenu(View v){
PopupMenu shapesPopUpMenu = new PopupMenu(this, v);

public boolean onMenuItemClick(MenuItem item) {
//How to determine which menu clicked?
return false;

Answer Source

It's not possible directly. You'd at least need to map the item ids item.getItemId() to the menu (button) they're connected to.

Maybe a little simpler might be using groups like: menu/colours_menu.xml

<menu xmlns:android="" >
    <group android:id="@+id/colours_menu" >
        <item android:id="@+id/item1" ... />
        <item android:id="@+id/item2" ... />
        <item android:id="@+id/item3" ... />

With item.getGroupId() you'd get the group ids and only need to map these to the buttons:

public boolean onMenuItemClick(MenuItem item) {
    if (item.getGroupId() == {
        // edit colors menu
    } else {
        // edit shape menu
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download