3

i have seen some tutorials but couldn't got through. I want to show icons along with item text. Here is my menu item.

  <item
    android:id="@+id/share"
    android:icon="@drawable/ic_share_grey600_18dp"
    app:showAsAction="always|withText"
    android:orderInCategory="1"
    android:title="Share"/>

Here is my java code :

PopupMenu popup = new PopupMenu(context, holder.cardMenuButton);
popup.getMenuInflater().inflate(R.menu.card_overflow_menu, popup.getMenu());
popup.show();

I am developing my app in material design. But its only showing the text.

Aleena
  • 273
  • 4
  • 12

2 Answers2

3

The simple answer is you can't. You can use a similar widget, ListPopWindow, which uses an adapter to draw its content, giving you the flexibility you need.

Edit. For the width problem you have to call setContentWidth. You can easily iterate on the adapter's dataset in order to calculate the max width, and use this value as parameter for setContentWidth

Blackbelt
  • 156,034
  • 29
  • 297
  • 305
1

Actually, you can, as you can see here: Is it possible to display icons in a PopupMenu?

Based on that answer, here is a custom class that shows icons:

public class PopupMenu extends androidx.appcompat.widget.PopupMenu {

public PopupMenu(Context context, View anchor) {
    super(context, anchor);
    setForceShowIcon();
}

public PopupMenu(Context context, View anchor, int gravity) {
    super(context, anchor, gravity);
    setForceShowIcon();
}

public PopupMenu(Context context, View anchor, int gravity,
                 int popupStyleAttr, int popupStyleRes) {
    super(context, anchor, gravity, popupStyleAttr, popupStyleRes);
    setForceShowIcon();
}

private void setForceShowIcon() {
    try {
        Field mPopup = androidx.appcompat.widget.PopupMenu.class
                .getDeclaredField("mPopup");
        mPopup.setAccessible(true);
        MenuPopupHelper popup = (MenuPopupHelper) mPopup.get(this);
        popup.setForceShowIcon(true);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
}
0101100101
  • 5,786
  • 6
  • 31
  • 55