android 如何在 PopupMenu 中显示图标和文本?

How to show icons along with text in PopupMenu in android?

我看过一些教程,但无法通过。我想显示图标和项目文本。这是我的菜单项。

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

这是我的 java 代码:

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

我正在 material 设计中开发我的应用程序。但它只显示文本。

简单的回答是你不能。您可以使用类似的小部件 ListPopWindow,它使用适配器来绘制其内容,从而为您提供所需的灵活性。

编辑。对于宽度问题你必须调用setContentWidth。您可以轻松地迭代适配器的数据集以计算最大宽度,并将此值用作 setContentWidth

的参数

实际上,您可以在这里看到:Is it possible to display icons in a PopupMenu?

根据该回答,这里是显示图标的自定义 class:

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);
    }
}
}