Skip to content Skip to sidebar Skip to footer

Popupmenu Not Showing Icons And How To Highlight Popupmenu Item When Its Opened

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_cam

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

Solution 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" />

Post a Comment for "Popupmenu Not Showing Icons And How To Highlight Popupmenu Item When Its Opened"