- 在Android官方开发规范中,有:PopupMenu DOES NOT INCLUDE/SHOW
ICONS,即:PopupMenu不应该展示图标。
但是,我们可以通过setForceShowIcon(true)方法,来强制显示添加的Icon。
方法一:继承PopupMenu的类MyPopupMenu:
public MyPopupMenu(Context context, View anchor) {
mContext = context;
mMenu = new MenuBuilder(context);
mMenu.setCallback(this);
mAnchor = anchor;
mPopup = new MenuPopupHelper(context, mMenu, anchor);
mPopup.setCallback(this);
mPopup.setForceShowIcon(true); //ADD THIS LINE
}
- 方法二:通过反射:
mPmAdd = new PopupMenu(this, button);
//reflection
try {
Field[] fields = mPmAdd.getClass().getDeclaredFields();
for (Field field : fields) {
if ("mPopup".equals(field.getName())) {
field.setAccessible(true);
Object menuPopupHelper = field.get(mPmAdd);
Class<?> classPopupHelper = Class.forName(menuPopupHelper
.getClass().getName());
Method setForceIcons = classPopupHelper.getMethod(
"setForceShowIcon", boolean.class);
setForceIcons.invoke(menuPopupHelper, true);
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
效果图: