I have an imageButton in a xml file. Now want to make it a menu button, so that when a user click on the button it should show the drop down menus. But I am not able to figure out what are the possible solution(s). Can anyone help?
Asked
Active
Viewed 3,860 times
1 Answers
10
If you're trying to show a drop down menu when clicking an ImageButton (or any other View), try this:
final ImageButton imageButton = // get your ImageButton from the XML here
final PopupMenu dropDownMenu = new PopupMenu(getContext(), imageButton);
final Menu menu = dropDownMenu.getMenu();
// add your items:
menu.add(0, 0, 0, "An item");
menu.add(0, 1, 0, "Another item");
// OR inflate your menu from an XML:
dropDownMenu.getMenuInflater().inflate(R.menu.some_menu, menu);
dropDownMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case 0:
// item ID 0 was clicked
return true;
case 1:
// item ID 1 was clicked
return true;
}
return false;
}
});
imageButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dropDownMenu.show();
}
});
// if you want to be able to open the menu by dragging on the button:
imageButton.setOnTouchListener(dropDownMenu.getDragToOpenListener());
When Android Studio asks to import PopupMenu you may see two options:
- android.support.v7.widget.PopupMenu this is the best option, it ensures your menu will work in any Android version
- android.widget.PopupMenu this one only works on Android 2.1 and up, which is probably fine. However, if new Android versions come with new features in PopupMenu, the first option may also let you use those new features in older Android versions.

Gil Castro
- 116
- 1
- 5
-
How to customize the color of this pop up menu? – Jul 01 '18 at 21:26
-
@Ashu_1907 I'm not sure this is the best way but try this (example with blue background and green text): In your themes.xml or styles.xml file add: ` ` Then replace `new PopupMenu(getContext(), imageButton)` with `new PopupMenu(new ContextThemeWrapper(getContext(), R.style.MenuTheme) imageButton)` – Gil Castro Jul 01 '18 at 21:48
-
I have tried the above code but the background color remains same but, the the color of the texts inside the pop up menu changes. – Jul 15 '18 at 13:03