I want to realize a custom popup menu like Twitter in Android for example with item and picture but I don\'t know what\'s the component used for that.
In Material
There's a widget called PopupMenu
which is basically a menu anchored to a specific view. One drawback is that it doesn't display icons by default.
However, you can use reflection and call setForceShowIcon
to reveal them. The code that you need is:
Since a PopupMenu
is anchored to a specific view, your ActionBar
item has an actionLayout
attribute. That layout (action_item.xml
) can be as simple as:
ActionBar
menu style that contains your item with the above layout
Your popup_menu.xml
, the layout you'll inflate for your PopupMenu
And finally code to perform the inflation when an ActionBar
item is clicked
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_add_item:
PopupMenu popup = new PopupMenu(this, item.getActionView());
MenuInflater inflater = popup.getMenuInflater();
inflater.inflate(R.menu.popup_menu, popup.getMenu());
// Use reflection to invoke setForceShowIcon
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.show();
return true;
}
return super.onOptionsItemSelected(item);
}
Note, that to get that multi-line text in a menu, you'd need to use an actionLayout
for your popup menu items too.