javaandroidmenulayout-inflaterandroid-inflate

Popup menu is not inflating


How can I create a custom popup menu class with OnMenuItemClickListeners? I can't seem to find any SO answers that use a seperate class to do so. They all do it in their activities, but I want a seperate popup menu class.

I've tried creating it:

public class AddPhotoMenu extends PopupMenu {
    public AddPhotoMenu(Context context, View anchor) {
        super(context, anchor);
    }

    @Override
    public void inflate(int menuRes) {
        super.inflate(R.menu.popup_menu_fragevent_addphotos);
    }

    @Override
    public void setOnMenuItemClickListener(OnMenuItemClickListener listener) {
        new OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                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;
            }
        };
    }

But the menu doesn't inflate when I call it.

 AddPhotoMenu addPhotoMenu = new AddPhotoMenu(this, mAddPhotosButton1);
 addPhotoMenu.show();

Solution

  • addPhotoMenu.inflate(R.menu.popup_menu_fragevent_addphotos);
    addPhotoMenu.setOnMenuItemClickListener(addPhotoMenu); 
    // Need to add this line otherwise it won't work.
    addPhotoMenu.show();
    

    Credits to:

    PopupMenu onMenuItemClick not being called