Zsombor Erdődy-Nagy Zsombor Erdődy-Nagy - 1 year ago 144
Android Question

Is it possible to display icons in a PopupMenu?

I really like the new PopupMenu we got in 3.0, but I just can't display any icons next to the menu items in it. I'm inflating the menu from the .xml below:

<item android:id="@+id/menu_delete_product"
android:showAsAction="ifRoom|withText" />

<item android:id="@+id/menu_modify_product"
android:showAsAction="ifRoom|withText" />

<item android:id="@+id/menu_product_details"
android:showAsAction="ifRoom|withText" />

With this code:

image.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
PopupMenu pop = new PopupMenu(getActivity(), v);
pop.getMenuInflater().inflate(R.menu.shelves_details_menu, pop.getMenu());

I can't get the icons to show up, am I missing something?

Answer Source

If you're willing to be a bit adventurous, look at Google's source code for PopupMenu. Create your own class i.e. MyPopupMenu that is the same as Google's PopupMenu class, but make one slight change.

In PopupMenu's constructor:

public MyPopupMenu(Context context, View anchor) {
    // TODO Theme?
    mContext = context;
    mMenu = new MenuBuilder(context);
    mAnchor = anchor;
    mPopup = new MenuPopupHelper(context, mMenu, anchor);
    mPopup.setForceShowIcon(true); //ADD THIS LINE


use the method setForceShowIcon to force it to show the icon. You can also just expose a public method to set this flag as well depending on your needs.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download