在硬件菜单按钮单击操作栏中打开子菜单 [英] Opening submenu in action bar on Hardware menu button click

查看:24
本文介绍了在硬件菜单按钮单击操作栏中打开子菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Title explains everything. I want to open a submenu in actionbar when clicking Hardware menu button

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

This is the code and it works fine first time i click menu. Every other time it just flashes(opens and the instantly closes it)

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

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

UPDATE:(Solution) Just changed onKeyDown() method to onKeyUp() and now it sticks

推荐答案

试试这个:

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

这篇关于在硬件菜单按钮单击操作栏中打开子菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆