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

后端 未结 4 1816
野性不改
野性不改 2020-12-16 15:29

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

Is it possible to set an onClickListener (or similar) on the button and if s

相关标签:
4条回答
  • 2020-12-16 15:43

    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.

    0 讨论(0)
  • 2020-12-16 15:53

    Updated for AppCompat v.22.+

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

    The solution is to override dispatchKeyEvent to this way:

    @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).

    0 讨论(0)
  • 2020-12-16 15:57

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

    /* (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);
    }
    
    0 讨论(0)
  • 2020-12-16 16:00

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

    0 讨论(0)
提交回复
热议问题