PopupMenu没有显示图标以及如何在打开时突出显示PopupMenu项目

时间:2014-12-25 07:47:47

标签: android image icons popupmenu

我正在使用android.support.v7中的PopupMenu。我试图用文字显示图标。但只显示文字。
我尝试使用普通代码:android:icon="@android:drawable/ic_menu_camera"但它不能与PopupMenu一起使用。

还有一个问题,我们可以在打开时突出显示PopupMenu项吗?

请在此处查看参考图像enter image description here

2 个答案:

答案 0 :(得分:3)

If you are using popup menu just copy the below code and run it, you will get icons in popupmenu

PopupMenu popup = new PopupMenu(getApplicationContext(), 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();
}

    popup.getMenuInflater()
                    .inflate(R.menu.publisher, popup.getMenu());

                    //registering popup with OnMenuItemClickListener
                    popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                        public boolean onMenuItemClick(MenuItem item) {

                            switch (item.getItemId()) {
                            case R.id.menu:
                                //your function
                                return true;
                                                        default:
                                break;
                            }
                            return false;
                        }
                    });
                    popup.show();

答案 1 :(得分:0)

更改自定义弹出式layout.xml

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Remove"
    android:drawableLeft="@drawable/ic_launcher"
    android:drawablePadding="5dp" />