问题
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?
回答1:
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.
回答2:
final ImageButton imageButton ;
final PopupMenu dropDownMenu = new PopupMenu(getContext(), imageButton);
final Menu menu = dropDownMenu.getMenu();
menu.add(0, 0, 0, "Item 1");
menu.add(0, 1, 0, "Item 2");
dropDownMenu.getMenuInflater().inflate(R.menu.some_menu, menu);
dropDownMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case 0:
return true;
case 1:
return true;
}
return false;
}
});
imageButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
dropDownMenu.show();
}
});
imageButton.setOnTouchListener(dropDownMenu.getDragToOpenListener());
来源:https://stackoverflow.com/questions/51126124/how-to-make-any-imagebutton-a-menu-button