我可以检测操作栏菜单按钮上的点击/点击,即用于显示溢出菜单项吗?
默认情况下,它会打开列表,其中包含一个项目"设置"。这是截图:
到目前为止,它正在检测点击" 2"但我想检测点击" 1"。
答案 0 :(得分:13)
要检测溢出菜单上的点击,请输入以下代码:
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
if(featureId == AppCompatDelegate.FEATURE_SUPPORT_ACTION_BAR && menu != null){
//overflow menu clicked, put code here...
}
return super.onMenuOpened(featureId, menu);
}
@Override
public void onPanelClosed(int featureId, Menu menu) {
...
}
要检测点击菜单项,以防你有这样的菜单:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu2" android:alphabeticShortcut="b"
android:title="Menu No. 2" android:orderInCategory="2">
<menu >
<group android:id="@+id/group2" android:checkableBehavior="single">
<item android:id="@+id/submenu1" android:title="SubMenu No. 1" />
<item android:id="@+id/submenu2" android:title="SubMenu No. 2" />
</group>
</menu>
</item>
</menu>
您应该能够检测到
中的点击onOptionsItemSelected
@Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.w("ANDROID MENU TUTORIAL:", "onOptionsItemSelected(MenuItem item)");
// Handle item selection
switch (item.getItemId()) {
case R.id.menu2:
Toast.makeText(this, "Clicked: Menu No. 2", Toast.LENGTH_SHORT).show();
return true;
...
}
答案 1 :(得分:1)
最后我找到了解决方案。覆盖FragmentActivity.onKeyDown
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
switch (keyCode) {
case KeyEvent.KEYCODE_MENU:
// Do Sometihng
break;
default:
break;
}
return super.onKeyDown(keyCode, event);
}
答案 2 :(得分:0)
默认情况下,点击溢出按钮会显示选项菜单,所以我相信您应设法拦截该事件,然后通过覆盖Activity.onPrepareOptionsMenu
来执行您想要的操作
这有点棘手,因为我找不到溢出按钮的ID,所以我使用了这个hack。
在Activity
:
private boolean actionBarClicked = false;
@Override
public boolean onOptionsItemSelected (MenuItem item) {
if (item.getId() == )
actionBarClicked = true;
return false; // Let default processing occur
}
@Override
public boolean onPrepareOptionsMenu (Menu menu) {
if (actionBarClicked) {
// Overflow button of ActionBar was clicked, do what you want here.
actionBarClicked = false;
}
...
}
答案 3 :(得分:0)
如果正确设置了工具栏和弹出菜单,只需在MainActivity
中使用这两个功能
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
//Perform some action on menu open
return super.onMenuOpened(featureId, menu);
}
@Override
public void onPanelClosed(int featureId, Menu menu) {
//Perform some action on menu closed
}
onCreate
的{{1}}功能中的设置工具栏
MainActivity
然后添加您在xml文件中定义的菜单
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
my_menu.xml
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.my_menu, menu);
return true;
}