打开子菜单在操作栏上的硬件菜单按钮点击(Opening submenu in action bar

2019-06-27 19:41发布

标题说明了一切。 我想在动作条打开子菜单点击硬件菜单按钮时

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

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

Answer 1:

试试这个:

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;
}


文章来源: Opening submenu in action bar on Hardware menu button click