我真的很喜欢我们在 3.0 中获得的新 PopupMenu,但我无法在其中的菜单项旁边显示任何图标。我正在从下面的 .xml 中扩充菜单:
<item android:id="@+id/menu_delete_product"
android:icon="@drawable/sym_action_add"
android:title="delete"
android:showAsAction="ifRoom|withText" />
<item android:id="@+id/menu_modify_product"
android:icon="@drawable/sym_action_add"
android:title="modify"
android:showAsAction="ifRoom|withText" />
<item android:id="@+id/menu_product_details"
android:icon="@drawable/sym_action_add"
android:title="details"
android:showAsAction="ifRoom|withText" />
使用此代码:
image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
PopupMenu pop = new PopupMenu(getActivity(), v);
pop.getMenuInflater().inflate(R.menu.shelves_details_menu, pop.getMenu());
pop.show();
}
});
我无法显示图标,是我遗漏了什么吗?
最佳答案
对 Gaelan Bolger 提供的解决方案的贡献。 如果您收到“IllegalAccessException: access to field not allowed”,请使用此代码。
PopupMenu popup = new PopupMenu(mContext, view);
try {
Field[] fields = popup.getClass().getDeclaredFields();
for (Field field : fields) {
if ("mPopup".equals(field.getName())) {
field.setAccessible(true);
Object menuPopupHelper = field.get(popup);
Class<?> classPopupHelper = Class.forName(menuPopupHelper
.getClass().getName());
Method setForceIcons = classPopupHelper.getMethod(
"setForceShowIcon", boolean.class);
setForceIcons.invoke(menuPopupHelper, true);
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
prepareMenu(popup.getMenu());
popup.show();
文字
关于android - 是否可以在 PopupMenu 中显示图标?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6805756/