问题
I have a class AddPhotoMenu
public class AddPhotoMenu extends PopupMenu implements PopupMenu.OnMenuItemClickListener {
public AddPhotoMenu(Context context, View anchor) {
super(context, anchor);
}
@Override
public boolean onMenuItemClick(MenuItem item) {
Log.d(TAG, "onMenuItemClick: Called");
switch (item.getItemId()) {
case R.id.popup_menu_fragevent_takephoto:
//Inflate a layout
Log.d(TAG, "onMenuItemClick: Take photo");
break;
case R.id.popup_menu_fragevent_selectphotos:
//Inflate a layout
Log.d(TAG, "onMenuItemClick: Select photo");
break;
}
return false;
}
}
And I create a new instance of it however the method onMenuItemClick is never called when I click on the menu items.
AddPhotoMenu addPhotoMenu = new AddPhotoMenu(this, mAddPhotosButton1);
addPhotoMenu.inflate(R.menu.popup_menu_fragevent_addphotos);
addPhotoMenu.show();
What is causing the issue?
Edit:__________________________________________________
XML of menu
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:id="@+id/popup_menu_fragevent_takephoto"
android:title="Take a photo"/>
<item
android:id="@+id/popup_menu_fragevent_selectphotos"
android:title="Select photos"/>
</menu>
回答1:
Try like this
@Override
public boolean onMenuItemClick(MenuItem item) {
Log.d(TAG, "onMenuItemClick: Called");
switch (item.getItemId()) {
case R.id.popup_menu_fragevent_takephoto:
//Inflate a layout
Log.d(TAG, "onMenuItemClick: Take photo");
return true; // return true instead of break
case R.id.popup_menu_fragevent_selectphotos:
//Inflate a layout
Log.d(TAG, "onMenuItemClick: Select photo");
return true; // return true instead of break
}
return false;
}
UPDATE:
You have to set MenuItemClickListener
to your popup menu like below.
AddPhotoMenu addPhotoMenu = new AddPhotoMenu(this, mAddPhotosButton1);
addPhotoMenu.inflate(R.menu.popup_menu_fragevent_addphotos);
addPhotoMenu.setOnMenuItemClickListener(addPhotoMenu); // add this line
addPhotoMenu.show();
回答2:
You PopupMenu.OnMenuItemClickListener should be implemented in the Activity or Fragment where you instantiate your PopupMen.
After that addPhotoMenu.setOnMenuItemClickListener(this)
should be called, where "this" represents your Fragment or Activity.
来源:https://stackoverflow.com/questions/59281744/popupmenu-onmenuitemclick-not-being-called