user3650602 user3650602 - 6 months ago 18
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 {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}

public void showColourPopUpMenu(View v){
PopupMenu coloursPopUpMenu = new PopupMenu(this, v);
coloursPopUpMenu.setOnMenuItemClickListener(this);
coloursPopUpMenu.inflate(R.menu.colours_menu);
coloursPopUpMenu.show();
}

public void showShapePopUpMenu(View v){
PopupMenu shapesPopUpMenu = new PopupMenu(this, v);
shapesPopUpMenu.setOnMenuItemClickListener(this);
shapesPopUpMenu.inflate(R.menu.shape_menu);
shapesPopUpMenu.show();
}

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

Answer

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="http://schemas.android.com/apk/res/android" >
    <group android:id="@+id/colours_menu" >
        <item android:id="@+id/item1" ... />
        <item android:id="@+id/item2" ... />
        <item android:id="@+id/item3" ... />
    </group>
</menu>

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

@Override
public boolean onMenuItemClick(MenuItem item) {
    if (item.getGroupId() == R.id.colours_menu) {
        // edit colors menu
    } else {
        // edit shape menu
    }
}
Comments