2

I am trying to override the behavior of the hardware menu button on Android to make it open the overflow menu in the ActionBar.

Thanks to this question, I am able to display the overflow menu in the ActionBar. But when I press the hardware menu button, the "normal" menu (at the bottom of the screen) opens instead, of the overflow menu.

I tried to change this by overriding the onKeyDown(int, KeyEvent) in my Activity, but it doesn't work.

if (keyCode == KeyEvent.KEYCODE_MENU) {
    // I am extending android.support.v7.app.ActionBarActivity
    this.getSupportActionBar().openOptionsMenu();

    return true;
}

After investigating, it seems that getSupportActionBar() returns an instance of android.support.v7.internal.app.WindowDecorActionBar, which return false in openOptionsMenu() instead of opening the menu.

Is there an other way to achieve this? Maybe trigger a click on the overflow icon directly? But how can I access it?

Community
  • 1
  • 1
Gaëtan
  • 11,912
  • 7
  • 35
  • 45

1 Answers1

0

It's been a long time since you've posted this but in case you didn't find the solution I share my experience.

Actually I was looking for the same behavior (you press menu key and the menu appears on the action bar, not at bottom of the screen, exactly like when you touch overflow icon, something like Telegram)

I override onKeyDown and onKeyUp methods like this:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch (keyCode) {
        case KeyEvent.KEYCODE_MENU:
            //Apparently does nothing but prevents menu pop up
            //at bottom of the screen
            return true;
        default:
            return super.onKeyDown(keyCode, event);
    }
}

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    switch (keyCode) {
        case KeyEvent.KEYCODE_MENU:
            getSupportActionBar().openOptionsMenu();
            return true;
        default:
            return super.onKeyUp(keyCode, event);
    }
}

I believe the code is self explanatory, also note that I set android.support.v7.widget.Toolbar as my action bar in onCreate method:

toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

Note: Actually the represented solution you mentioned above is not recommended, (why? lack of consistency) I recommend to use android.support.v7.widget.Toolbar, something like Blank Activitiy template that Android Studio creates for you. (take a careful look at code, themes and layouts please)

Community
  • 1
  • 1
Farshad
  • 3,074
  • 2
  • 30
  • 44