在硬件菜单按钮上的操作栏中打开子菜单单击

时间:2012-09-05 08:21:29

标签: android menu android-actionbar

标题解释了一切。我想在单击“硬件”菜单按钮

时在操作栏中打开子菜单

这是代码,第一次单击菜单时工作正常。每隔一次它就会闪烁(打开并立即关闭)

private Menu mainMenu;
public boolean onCreateOptionsMenu(Menu menu) {

MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options, menu);
mainMenu = menu;

return true;
}

public boolean onKeyDown(int keyCode, KeyEvent event) {
if(event.getAction() == KeyEvent.ACTION_DOWN){
    switch(keyCode) {
    case KeyEvent.KEYCODE_MENU:

        mainMenu.performIdentifierAction(R.id.more, 0);

        return true;  
    }
}
return super.onKeyDown(keyCode, event);
}

这里是options.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item
    android:id="@+id/settings"
    android:icon="@drawable/ic_menu_preferences"
    android:showAsAction="ifRoom|withText"
    android:title="Settings"/>

<item
    android:id="@+id/about"
    android:icon="@drawable/ic_menu_info_details"
    android:showAsAction="ifRoom|withText"
    android:title="About"/>

<item
    android:id="@+id/more"
    android:icon="@drawable/ic_menu_moreoverflow_normal_holo_dark"
    android:showAsAction="always|withText"
    android:title="More">
    <menu>
        <item
    android:id="@+id/changelog"
    android:icon="@drawable/ic_menu_recent_history"
    android:showAsAction="ifRoom|withText"
    android:title="Changelog"/>
        <item
    android:id="@+id/update"
    android:icon="@drawable/ic_menu_refresh"
    android:showAsAction="ifRoom|withText"
    android:title="Update Check"/>
<item
    android:id="@+id/check"
    android:icon="@drawable/ic_menu_help"
    android:showAsAction="ifRoom|withText"
    android:title="Compatibility Check"/>
        </menu> 
        </item>

</menu>

更新:(溶液) 刚刚将onKeyDown()方法更改为onKeyUp(),现在它已经粘贴了

1 个答案:

答案 0 :(得分:6)

试试这个:

public boolean onCreateOptionsMenu(Menu menu) 
{
    super.onCreateOptionsMenu(menu);// <--- add this

    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.options, menu);
    mainMenu = menu;
    return true;
}

//override this method instead of onKeyDown()....
@Override
public boolean onOptionsItemSelected(MenuItem item) 
{
    super.onOptionsItemSelected(item);      

    int menuId = item.getItemId();      
    if(menuId == R.id.settings)
    {
        //do settings   
    }
    //else if(menuId = ...) {....}

    return true;
}