如果你想创建一个上下文菜单,你必须调用该方法registerForContextMenu()
向其传递应与上下文菜单关联的视图。
例如,假设将上下文菜单与按钮关联:
Button button = (Button) findViewById(R.id.my_button);
registerForContextMenu(button);
可以在 Activity 的 onCreate() 中调用它。然后,在同一个活动中,您需要覆盖onCreateContextMenu()
method.
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.your_context_menu, menu);
}
然后你必须实施onContextItemSelected()
,用于在按下上下文菜单中的项目时触发正确的操作:
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.first_action:
// your first action code
return true;
case R.id.second_action:
// your second action code
return true;
default:
return super.onContextItemSelected(item);
}
}
现在,长按按钮将打开您在中定义的上下文菜单your_context_menu.xml
file.
考虑到长按打开上下文菜单符合 Android 标准 UI,但是如果您希望单击一下即可显示上下文菜单,您可以查看答案在这里 https://stackoverflow.com/a/2981882/1584654
NOTE:正如所说here http://developer.android.com/guide/topics/ui/declaring-layout.html#attributes
ID 在整个树中不必是唯一的,但应该是
在您正在搜索的树的部分中是唯一的(这通常可能是
是整棵树,所以最好是完全唯一的
可能的)。