user8274134
user8274134

Reputation:

How to make any imagebutton a menu button

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?

Upvotes: 5

Views: 4205

Answers (1)

Gil Castro
Gil Castro

Reputation: 116

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:

  1. android.support.v7.widget.PopupMenu this is the best option, it ensures your menu will work in any Android version
  2. 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.

Upvotes: 10

Related Questions