PopupMenu with icons

Alex picture Alex · Mar 16, 2013 · Viewed 86.2k times · Source

Of course we are dealing here with SDK 11 and above.

I intend to do something similar to this: enter image description here

Next to each item in that PopupMenu, I would like to place an icon.

I created an XML file and placed it in /menu:

<menu xmlns:android="http://schemas.android.com/apk/res/android" >

    <item
        android:id="@+id/action_one"
        android:title="Sync"
        android:icon="@android:drawable/ic_popup_sync"
        />

    <item
        android:id="@+id/action_two"
        android:title="About"
        android:icon="@android:drawable/ic_dialog_info"
        />
</menu>

As you noticed, in the xml file I am defining the icons I want, however, when the popup menu shows, it is showing them without the icons. What should I do to make those 2 icons appear?

Answer

Stephen Kidson picture Stephen Kidson · Aug 18, 2016

This way works if you're using AppCompat v7. It's a little hacky but significantly better than using reflection and lets you still use the core Android PopupMenu:

PopupMenu menu = new PopupMenu(getContext(), overflowImageView);
menu.inflate(R.menu.popup);
menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { ... });

MenuPopupHelper menuHelper = new MenuPopupHelper(getContext(), (MenuBuilder) menu.getMenu(), overflowImageView);
menuHelper.setForceShowIcon(true);
menuHelper.show();

res/menu/popup.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:id="@+id/menu_share_location"
        android:title="@string/share_location"
        android:icon="@drawable/ic_share_black_24dp"/>

</menu>


This results in the popup menu using the icon that is defined in your menu resource file:

enter image description here