18

标题说明一切。单击硬件菜单按钮时,我想在操作栏中打开子菜单

这是代码,它在我第一次单击菜单时运行良好。每隔一段时间它就会闪烁(打开并立即关闭它)

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() 现在它坚持了

4

1 回答 1

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;
}
于 2012-09-05T08:40:42.857 回答