4

I know I can override onBackPressed() on higher API levels to detect if the back key is pressed. Is there a similar way to do it for the menu button? I'm not a big fan of checking keycode in KeyEvents. Thanks!

WSBT
  • 33,033
  • 18
  • 128
  • 133

2 Answers2

16

Are you in search of this????:

public boolean onKeyDown(int keyCode, KeyEvent event) { 
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            //do your work
            return true;
        }
        return super.onKeyDown(keyCode, event); 
    } 
Hanry
  • 5,481
  • 2
  • 40
  • 53
  • Thanks. I knew this method, but I'm not a big fan of checking keycode. I wanted something similar to `onBackPressed()`, not `if (keyCode == KeyEvent.KEYCODE_BACK)`. – WSBT Nov 26 '11 at 16:25
  • 2
    If you take a look at the first few lines of the Activity source code, you will see that onBackPressed is called following the Back button keyCode: http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/4.3_r2.1/android/app/Activity.java#Activity.onKeyDown%28int%2Candroid.view.KeyEvent%29 – Lior Oct 16 '13 at 01:17
  • 1
    Does this still work with API 22? I have an app where the event does not fire on Home or Menu keys. – Alen Siljak Mar 12 '15 at 23:10
  • I have tried the same code but can't succeed in Oppo F3. – Arun-Khanka May 24 '19 at 12:32
5

If you are just looking to create a key listener for the menu button you should be overriding onKeyDown and checking the keycode. Now since you pointed out that you are not a big fan of that you could also override onPrepareOptionsMenu which is called everytime the menu button is clicked and a menu is shown to the user. I am not sure if this is called if you have not supplied a menu inside the onCreateOptionsMenu method.

Bobbake4
  • 24,509
  • 9
  • 59
  • 94
  • Thanks, this works. I ended up inflating menu object in `onCreateOptionsMenu()` and overrode `onOptionsItemSelected()`. – WSBT Nov 26 '11 at 16:28
  • @bobbake4 how to listen when the menu is pressed second time public void onOptionMenuClosed() is not working. – Abhijit Chakra Mar 27 '13 at 06:50
  • With no options menu defined on android 4.4.2, onPrepareOptionsMenu is only called right when activity starts and never again. – velis Feb 11 '14 at 07:53
  • @velis You can use the call invalidateOptionsMenu() or supportInvalidateOptionsMenu() to cause a menu rebuild to happen. – Bobbake4 Feb 11 '14 at 15:12
  • It should not work.. I gave down vote to this answer because its not even work or not a proper answer. I will share you my answer – Ahmad Arslan Apr 15 '15 at 10:27