java Android:如何为 MenuButton 设置侦听器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2478418/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 21:22:47  来源:igfitidea点击:

Android: How can I set a listener to the MenuButton?

javaandroidoptionmenu

提问by whlk

I want to do a custom action when pressing on the Menubutton on the phone.

我想在按下Menu手机上的按钮时执行自定义操作。

Is it possible to set an onClickListener (or similar) on the button and if so, how?

是否可以在按钮上设置 onClickListener(或类似的),如果可以,如何设置?

onCreateOptionsMenuis only called the first time the button is pressed - I've already tried this.

onCreateOptionsMenu仅在第一次按下按钮时调用 - 我已经试过了。

回答by Diego Torres Milano

Usually you shouldn't override MENUbehavior as users expect menu to appear, however you can use something along these lines:

通常你不应该MENU在用户期望菜单出现时覆盖行为,但是你可以使用以下内容:

/* (non-Javadoc)
 * @see android.app.Activity#onKeyDown(int, android.view.KeyEvent)
 */
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ( keyCode == KeyEvent.KEYCODE_MENU ) {
        Log.d(TAG, "MENU pressed");
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

回答by yanchenko

But onPrepareOptionsMenu(..)is called each time. :)

但是onPrepareOptionsMenu(..)每次都被调用。:)

回答by danigonlinea

Updated for AppCompat v.22.+

更新了 AppCompat v.22.+

As mentioned in this forum, KeyDownis not called for KEYCODE_MENU button pressed.

如本论坛所述KeyDown按下 KEYCODE_MENU 按钮不会调用。

The solution is to override dispatchKeyEventto this way:

解决方案是覆盖dispatchKeyEvent这种方式:

@Override
public boolean dispatchKeyEvent(KeyEvent event) {
    int keyCode = event.getKeyCode();
    int action = event.getAction();
    boolean isDown = action == KeyEvent.ACTION_DOWN;

    if (keyCode == KeyEvent.KEYCODE_MENU) {
        return isDown ? this.onKeyDown(keyCode, event) : this.onKeyUp(keyCode, event);
    }

    return super.dispatchKeyEvent(event);
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    if ( keyCode == KeyEvent.KEYCODE_MENU ) {
        // do what you want to do here
        return true;
    }

    return super.onKeyDown(keyCode, event);
}

It works until Google developers release a fix for this (or maybe it is not a bug and it works this way from now on).

在 Google 开发人员为此发布修复程序之前,它一直有效(或者它可能不是错误并且从现在开始就以这种方式工作)。

回答by Cheryl Simon

You could probably hack something in using "OnMenuOpened" or some such, but I really wouldn't recommend it. The menu button is only supposed to be used to show menus, so there is consistency between applications.

你可能会在使用“OnMenuOpened”或类似的东西时破解一些东西,但我真的不推荐它。菜单按钮仅用于显示菜单,因此应用程序之间具有一致性。