0

Using onKeyDown with KEYCODE_MENU do nothing but it work with KEYCODE_SEARCH

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch(keyCode){
        case KeyEvent.KEYCODE_MENU:
            Toast.makeText(this, "Menu key pressed", Toast.LENGTH_SHORT).show();
            return false;
        case KeyEvent.KEYCODE_SEARCH:
            Toast.makeText(this, "Search key pressed", Toast.LENGTH_SHORT).show();
            return false;
    }
    return super.onKeyDown(keyCode, event);
}

I think there is something handling the menu key so it won't listen to my code i have tried disbling onCreateOptionsMenu like this:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    return true;
}

But still won't work..
So, any ideas to make the menu button listen to onKeyDown??

MostafaZ4
  • 43
  • 8

3 Answers3

3

This may be a bug in appcompat v22. See https://code.google.com/p/android/issues/detail?id=159795

The workaround as posted in that thread is to override dispatchKeyEvent :

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

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

        return super.dispatchKeyEvent(event);
    }

Edit: Please see Upgraded to AppCompat v22.1.0 and now onKeyDown and onKeyUp are not triggered when menu key is pressed

Community
  • 1
  • 1
headuck
  • 2,763
  • 16
  • 19
1

Even in use of Setup Box and Android TV you can use dispatchKeyEvent in Activity and after that detect any key you want

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

    if (code == KeyEvent.KEYCODE_MENU) {
        Toast.makeText(this, "Menu Is Selected", Toast.LENGTH_SHORT).show();
    }

    return super.dispatchKeyEvent(event);
}
deHaar
  • 17,687
  • 10
  • 38
  • 51
H.Fa8
  • 318
  • 3
  • 10
0

What device and OS are you on ?

You may want to update your compat library to the latest .. 23.0.0

arbrcr
  • 815
  • 4
  • 7