Catch keypress with android

You can either handle key events from a view or in general for your whole application:

Handle onKey from a View:

public boolean onKey(View v, int keyCode, KeyEvent event) {
    switch (keyCode) {
        case KeyEvent.KEYCODE_ENTER:
         /* This is a sample for handling the Enter button */
      return true;
    }
    return false;
}

Remember to implement OnKeyListener and to set your listener YourView.setOnKeyListener(this);

The second possibility would be:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
     switch (keyCode) {
     case KeyEvent.KEYCODE_MENU:
        /* Sample for handling the Menu button globally */
        return true;
     }
     return false;
} 

You could also ta a look at onKeyUp.

Resource: http://developer.android.com/reference/android/view/View.html

And here you can see a list with all KeyEvents

Leave a Comment