如何在android的弹出菜单中显示图标和文本?

如何在android的弹出菜单中显示图标和文本?,android,android-5.0-lollipop,android-popupwindow,Android,Android 5.0 Lollipop,Android Popupwindow,我看过一些教程,但没看完。我想显示图标和项目文本。这是我的菜单 <item android:id="@+id/share" android:icon="@drawable/ic_share_grey600_18dp" app:showAsAction="always|withText" android:orderInCategory="1" android:title="Share"/> 我正在开发我的材料设计应用程序。但它只是显示文本

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

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

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

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


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

的参数。实际上,您可以,如您在此处所见:

根据该答案,下面是一个显示图标的自定义类:

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

好的,让我试试这个,thnxThnx,精确解。你想在actionbar或overflow菜单中显示吗?我使用的是CardView,我在CardView的右角放了一个overflow的操作按钮。单击该按钮后,我需要显示一个弹出菜单,将
app:showAsAction=“always | withText”
更改为
app:showAsAction=“never”
抱歉,但它不起作用
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);
    }
}
}