如何使任何图像按钮成为菜单按钮

How to make any imagebutton a menu button

我在 xml 文件中有一个 imageButton。现在想把它做成一个菜单按钮,这样当用户点击按钮时它应该显示下拉菜单。但我无法弄清楚可能的解决方案是什么。 有人可以帮忙吗?

如果您尝试在单击 ImageButton(或任何其他 View)时显示下拉菜单,请尝试以下操作:

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());

当 Android Studio 要求导入 PopupMenu 时,您可能会看到两个选项:

  1. android.support.v7.widget.PopupMenu 这是最好的选择,它确保您的菜单在任何 Android 版本
  2. android.widget.PopupMenu 这个只适用于 Android 2.1 及更高版本,这可能没问题。但是,如果新 Android 版本在 PopupMenu 中带有新功能,第一个选项也可以让您在旧 Android 版本中使用这些新功能。