How to capture key pad presses in an Activity.

To capture the keypad presses and any other keys on the phone…
Override the Activities OnKeyDown and compare the keycode against one of the constants in KeyEvent.KEYCODE_*

        @Override
        public boolean onKeyDown(int keyCode, KeyEvent ev) {
                switch (keyCode) {
                case KeyEvent.KEYCODE_DPAD_LEFT:
                        // do something
                        return true;
                case KeyEvent.KEYCODE_DPAD_RIGHT:
                        // do something
                        return true;
                default:
                                return super.onKeyDown(keyCode, ev);
                }
        }
 

A couple of things to note are, returning true informs the caller that you have handled the keypress and it does not need to propagate to other views. Don’t forget to return the result of super.onKeyDown as the last resort or you’ll find out the default handling of keys no longer gets processed for your activity. (e.g. the back button will no longer navigate back through the Activity stack)

Leave a Reply