我在xml文件中有一个imageButton。现在,要使其成为菜单按钮,以便用户单击该按钮时应显示下拉菜单。但是我无法找出可能的解决方案。 有人可以帮忙吗?
答案 0 :(得分:2)
如果您尝试在单击 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 :(得分:0)
[0, -2.36]