【问题标题】:How to show icons along with text in PopupMenu in android?如何在 android 的 PopupMenu 中显示图标和文本?
【发布时间】:2021-04-16 09:45:42
【问题描述】:

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

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

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

【问题讨论】:

  • 您要显示在操作栏还是溢出菜单中?
  • 我正在使用 CardView,并且我在该 cardview 的右上角放置了一个溢出操作按钮。点击那个 aciton 按钮,我需要显示一个弹出菜单,
  • app:showAsAction="always|withText" 更改为app:showAsAction="never"
  • 抱歉,没用

标签: android android-5.0-lollipop android-popupwindow


【解决方案1】:

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

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

【讨论】:

  • 好吧,让我试试那个,thnx
  • Thnx,精确的解决方案。
【解决方案2】:

实际上,您可以,如您在此处看到的:Is it possible to display icons in a PopupMenu?

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-13
    • 2015-01-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多