Original address: http://android.xsoftlab.net/training/keyboard-input/commands.html
When the user focuses the focus on the view of the editable text, such as EditText, and the device has an entity keyboard, all input is processed by the system. However, if you want to be able to intercept or directly handle keyboard input events, you can do so by implementing the callback method Keyevent.callback interface. such as onkeydown () and Onkeymultiple ().
Both activity and view implement the Keyevent.callback interface, so you should override the callback methods of these two classes in general.
Note: When you handle input events for the keyboard through the KeyEvent class or other related APIs, you should consider these keyboard events to come from the physical keyboard. Never rely on key events that receive a soft keyboard.
Handling Single keystroke events
If you want to handle independent keystroke events, you need to use the onkeydown () method or the OnKeyUp () method appropriately. Typically, you should only use the onkeyup () method if you want to ensure that only one key is pressed. If the user presses and does not release a button, then onkeydown () will be called multiple times.
For example, the following implementation controls the game by responding to certain keystrokes:
@Override Public Boolean onKeyUp(intKeyCode, KeyEvent event) {Switch(KeyCode) { CaseKeyEvent.KEYCODE_D:moveShip (Move_left);return true; CaseKeyEvent.KEYCODE_F:moveShip (Move_right);return true; CaseKeyEvent.KEYCODE_J:fireMachineGun ();return true; CaseKeyEvent.KEYCODE_K:fireMissile ();return true;default:return Super. OnKeyUp (KeyCode, event); }}
Handling Combination Keys
In response to a combination of key events, such as some keys that need to be combined with shift or control, you can query the KeyEvent object returned by the callback method. Some methods also provide the function of querying information for the combination of keys, such as getmodifiers () and Getmetastate (). In any case, the simplest solution is to check whether the combination keys you care about are pressed through isshiftpressed () or isctrlpressed ().
For example, the following is an improved version of the OnKeyUp () method, which adds some extra processing specifically for the SHIFT key:
@Override Public Boolean onKeyUp(intKeyCode, KeyEvent event) {Switch(KeyCode) { ... CaseKeyevent.keycode_j:if(Event.isshiftpressed ()) {Firelaser (); }Else{Firemachinegun (); }return true; CaseKeyevent.keycode_k:if(Event.isshiftpressed ()) {Fireseekingmissle (); }Else{Firemissile (); }return true;default:return Super. OnKeyUp (KeyCode, event); }}
Android Official Development Document Training Series Course Chinese version: keyboard input processing keyboard keys