使用菜单按钮打开子菜单

使用菜单按钮打开子菜单

本文介绍了ActionBarSherlock:使用菜单按钮打开子菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 ActionBarSherlock-4.1.0-0,我想使用硬件菜单按钮在操作栏中打开我的子菜单.我正在计划更新,在我的旧版本中,我使用了普通"菜单.我想帮助用户适应新设计.

I'm using ActionBarSherlock-4.1.0-0 and I would like to open my submenu in the Actionbar with the hardware menu button. I'm planing an update and in my old version I used the "normal" menu. I'd like to help users to get used to the new design.

我有子菜单和主菜单:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater i = getSupportMenuInflater();
    i.inflate(R.menu.main_menu, menu);
    SubMenu subMenu = (SubMenu) menu.findItem(R.id.actionbar_submenu);
    Menu mainMenu = menu;
    return super.onCreateOptionsMenu(menu);
}

我得到了硬件菜单按钮的监听器:

and I got a listener to the hardware menu button:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(event.getAction() == KeyEvent.ACTION_DOWN){
        switch(keyCode) {
        case KeyEvent.KEYCODE_MENU:
            // TODO: expand submenu from actionbar
            return true;

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

我找不到要调用的方法或其他任何东西.

I couldn't find a method or anything else to call.

推荐答案

我尝试使用 Frederik 的这个解决方案和 android actionbar,但遇到了子菜单立即打开和关闭的问题.更改为 onKeyUp 解决了这个问题.

I try this solution from Frederik with android actionbar and I run into the problem that the submenu opens and closes immediately. Changing to onKeyUp solved this issue.

这是我的代码:

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if(keyCode == KeyEvent.KEYCODE_MENU){
        if (event.getAction() == KeyEvent.ACTION_DOWN && optionsMenu != null && optionsMenu.findItem(R.id.sub_menu) != null)
        {
            Log.i(TAG, "performIdentifierAction");
            optionsMenu.performIdentifierAction(R.id.sub_menu, 0);
            return true;
        }
    }
    return super.onKeyUp(keyCode, event);
}

我会检查 optionsMenu != null &&optionsMenu.findItem(R.id.sub_menu) != null 因为与没有操作栏的旧 Android 版本的兼容性问题.如果您对所有版本都使用 ActionBarSherlock,这不是必需的.

I do check if optionsMenu != null && optionsMenu.findItem(R.id.sub_menu) != null because of compatibility issues with older Android versions without actionbar. This isn't nessesary if you use ActionBarSherlock for all versions.

这篇关于ActionBarSherlock:使用菜单按钮打开子菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 20:30