Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to display icons in a PopupMenu?

I really like the new PopupMenu we got in 3.0, but I just can't display any icons next to the menu items in it. I'm inflating the menu from the .xml below:

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

With this code:

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

I can't get the icons to show up, am I missing something?

like image 262
Zsombor Erdődy-Nagy Avatar asked Jul 24 '11 08:07

Zsombor Erdődy-Nagy


People also ask

How do I show the pop up menu on Android?

Go to app > res > right-click > New > Android Resource Directory and give Directory name and Resource type as menu. Now, we will create a popup_menu file inside that menu resource directory. Go to app > res > menu > right-click > New > Menu Resource File and create a menu resource file and name it as popup_menu.

What is popup menu in Android?

A PopupMenu displays a Menu in a modal popup window anchored to a View . The popup will appear below the anchor view if there is room, or above it if there is not. If the IME is visible the popup will not overlap it until it is touched. Touching outside of the popup will dismiss it.


1 Answers

Contribution to the solution provided by Gaelan Bolger. Use this code if you get a "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(); 

text

like image 144
dgtale Avatar answered Oct 06 '22 02:10

dgtale