0

I'm trying to dynamically create a Popup Menu using Android's built-in PopupMenu class. No matter what I try, I'm unable to get the setIcon function to display anything. I've pared down my code to a pretty simple example:

public void showPopupMenu(View v) {
    popupMenu = new PopupMenu(this, v);
    popupMenu.setOnMenuItemClickListener(this);
    MenuItem menuItem = popupMenu.add("Menu Item 1");
    menuItem.setIcon(DrawableResource);
    popupMenu.show();
}

The menu shows up with only the text of the menu item. The resolution of the drawable is 40x40. If I try the same thing from XML, the icon shows up just fine. Any help figuring out what might be wrong is appreciated.

WavyGravy
  • 131
  • 1
  • 3
  • Does this answer your question? [PopupMenu with icons](https://stackoverflow.com/questions/15454995/popupmenu-with-icons) – Zain Jan 05 '21 at 19:38
  • I noticed another weird behavior. If I create a submenu programmatically, and then add an item to the submenu along with an icon, it works fine for the submenu. It just won't work for the main menu. This is strange since I remember reading somewhere that submenus don't support icons. – WavyGravy Jan 05 '21 at 21:26
  • Zain, thanks for the link. The link you sent me to contains some potential work-arounds. This seems to confirm that adding an Icon to a Popup Menu simply doesn't work, even though the documentation, and the Android API, attempts to support this feature. This seems like a blatant bug that Android should fix. – WavyGravy Jan 06 '21 at 20:01

1 Answers1

0

I note an error in the value passed to the setIcon method. You need to get your drawable resource image by doing

menuItem.setIcon(R.drawable.NameOfYourDrawableFile);

For instance, if the name of your drawable resource image is image.png, then you should do:

menuItem.setIcon(R.drawable.image);