PopupMenu not showing icons and how to highlight PopupMenu item when its opened

有些话、适合烂在心里 提交于 2020-01-06 06:39:48

问题


I am using PopupMenu from android.support.v7. I am trying to show icons with text. But only text is showing.
I tried to used normal code: android:icon="@android:drawable/ic_menu_camera" but its not working with PopupMenu.

One more question, can we highlight PopupMenu item when its opened ?

Please check the reference image here


回答1:


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



回答2:


Change your custom popup 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" />


来源:https://stackoverflow.com/questions/27645271/popupmenu-not-showing-icons-and-how-to-highlight-popupmenu-item-when-its-opened

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!