带有图标的PopupMenu

当然,我们这里使用的是SDK 11及更高版本。


我打算做类似的事情: 

我想在其中每个项目旁边PopupMenu放置一个图标。


我创建了一个XML文件并将其放在中/menu:


<menu xmlns:android="http://schemas.android.com/apk/res/android" >


    <item

        android:id="@+id/action_one"

        android:title="Sync"

        android:icon="@android:drawable/ic_popup_sync"

        />


    <item

        android:id="@+id/action_two"

        android:title="About"

        android:icon="@android:drawable/ic_dialog_info"

        />

</menu>

您已经注意到,在xml文件中,我正在定义所需的图标,但是,当弹出菜单显示时,它显示的是没有图标的图标。我应该怎么做才能使这两个图标出现?


慕尼黑8549860
浏览 951回答 3
3回答

繁星点点滴滴

Android弹出菜单有一个隐藏的方法来显示菜单图标。使用Java反射将其启用,如下所示。public static void setForceShowIcon(PopupMenu popupMenu) {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; Field[] fields = popupMenu.getClass().getDeclaredFields();&nbsp; &nbsp; &nbsp; &nbsp; for (Field field : fields) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if ("mPopup".equals(field.getName())) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; field.setAccessible(true);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Object menuPopupHelper = field.get(popupMenu);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Class<?> classPopupHelper = Class.forName(menuPopupHelper&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .getClass().getName());&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Method setForceIcons = classPopupHelper.getMethod(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "setForceShowIcon", boolean.class);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; setForceIcons.invoke(menuPopupHelper, true);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; } catch (Throwable e) {&nbsp; &nbsp; &nbsp; &nbsp; e.printStackTrace();&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Android