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;
}
}
@Override
public boolean onMenuItemClick(MenuItem item) {
int id = item.getItemId()
switch(id) {
case R.id.item1:
return true;
case R.id.item2:
return true;
default:
return false;
}
}
Create the listener when asigning it.
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
return true;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With