Listening for Key Events

Handling keystroke input across multiple platforms can be very tricky. Some devices have many more keys than others, some require triple-tapping for character input, and so on. This is a great example of something that should be left to the framework (EditText or one of its subclasses) whenever possible.

To extend a widget's KeyEvent handling, use the View method setOnKeyListener to install an OnKeyListener. The listener will be called with multiple KeyEvents for each user keystroke, one for each action type: DOWN, UP, and MULTIPLE. The action types DOWN and UP indicate a key was pressed or released, just as they did for the MotionEvent class. A key action of MULTIPLE indicates that a key is being held down (autorepeating). The KeyEvent method getRepeatCount gives the number of keystrokes that a MULTIPLE event represents.

Example 10-10 shows a sample key handler. When added to the demo program, it causes dots to be added to the display at randomly chosen coordinates when keys are pressed and released: a magenta dot when the Space key is pressed and released, a yellow dot when the Enter key is pressed and released, and a blue dot when any other key is pressed and released.

Example 10-10. Handling keys dotView.setFocusable(true);

dotView.setOnKeyListener(new OnKeyListener() {

^Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (KeyEvent.ACTION_UP != event.getAction()) { int color = Color.BLUE; switch (keyCode) {

case KeyEvent.KEYCODE_SPACE: color = Color.MAGENTA; break;

case KeyEvent.KEYCODE_ENTER: color = Color.YELLOW; break; default: ;

makeDot(dots, dotView, color);

0 0

Post a comment