我已经为按下ActionBar上的项目后显示的菜单实现了PopupMenu.我想知道11之前的SDK版本有哪些替代方案?
可能使用类似上下文菜单的东西.你的想法是什么?
我当前的实现是使用菜单项加载一个新的Activity.
gak*_*gak 13
正如@sastraxi建议的那样,一个很好的解决方案是使用AlertDialogwith CHOICE_MODE_SINGLE.
AlertDialog.Builder builder = new AlertDialog.Builder(MyAndroidAppActivity.this);
builder.setTitle("Pick color");
builder.setItems(R.array.colors, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
}
});
builder.setInverseBackgroundForced(true);
builder.create();
builder.show();
Run Code Online (Sandbox Code Playgroud)
和strings.xml文件.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="colors">
<item >blue</item>
<item >white</item>
</string-array>
</resources>
Run Code Online (Sandbox Code Playgroud)
参考:添加列表
或者,您可以使用浮动上下文菜单.
(3年后,实际上读取浮动上下文菜单仅适用于长时间点击并匆忙编辑答案).
您需要为上下文菜单注册视图,打开菜单,然后取消注册(以便长按操作项不再触发它):
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.my_menu_item) {
View view = item.getActionView();
registerForContextMenu(view);
openContextMenu(view);
unregisterForContextMenu(view);
return true;
}
return super.onOptionsItemSelected(item);
}
Run Code Online (Sandbox Code Playgroud)
当然,onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)按照链接的文档实现.
如OP所写,更好的选择是在这种特殊情况下使用AlertDialog,如果你想要一个居中的对话框,或者如果你想让菜单锚定到动作项,则使用PopupMenu.弹出菜单可能很奇怪,因为它会感觉像溢出菜单.