android点击按钮弹出上下文菜单
对于ListView的子项长按弹出上下文菜单是比较常见的操作,流程是先设置长按事件(setOnLongClickListener)返回false 来允许触发创建上下文菜单listener(setOnCreateContextMenuListener) 然后添加菜单项 最后点击菜单时会调用onContextItemSelected
而对于Button的话需要主动调用showContextMenu方法来触发创建上下文菜单listener
大致代码如下
private Button mBtnShowMenu; mBtnShowMenu = (Button)findViewById(R.id.btn_showmenu); // 点击弹出菜单 mBtnShowMenu.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { mBtnShowMenu.showContextMenu(); } }); // 创建上下文菜单listener mBtnShowMenu.setOnCreateContextMenuListener(new OnCreateContextMenuListener() { @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { menu.add(0,1,0,"选项1"); menu.add(0,2,0,"选项2"); } }); // 选择上下文菜单 @Override public boolean onContextItemSelected(MenuItem item) { switch (item.getGroupId()) { case 0: { switch (item.getItemId()) { case 1: { // 点击选项1 }break; case 2: { // 点击选项2 }break; } // end get item id } default:break; } return true; }