问题
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