Documentation KeyEvent.getUnicodeChar() reports
Returns 0 if the key is not used to enter Unicode characters.
Thus, it is easy to distinguish text codes from control codes, for example:
if (keyEvent.getUnicodeChar() != 0) { // unicode text char unicodeChar = (char) keyEvent.getUnicodeChar(); } else { // control char }
Here is a list that helped me reach this agreement:
// keyCode, Unicode, char, keyCode name 0 0 KEYCODE_UNKNOWN 1 0 KEYCODE_SOFT_LEFT 2 0 KEYCODE_SOFT_RIGHT 3 0 KEYCODE_HOME 4 0 KEYCODE_BACK 5 0 KEYCODE_CALL 6 0 KEYCODE_ENDCALL 7 48 0 KEYCODE_0 8 49 1 KEYCODE_1 9 50 2 KEYCODE_2 10 51 3 KEYCODE_3 11 52 4 KEYCODE_4 12 53 5 KEYCODE_5 13 54 6 KEYCODE_6 14 55 7 KEYCODE_7 15 56 8 KEYCODE_8 16 57 9 KEYCODE_9 17 42 * KEYCODE_STAR 18 35
Dead keys
Please note that you may also need to accept dead keys . docs say
The system recognizes the following Unicode characters as a combination of diacritical dead key characters.
'\u0300' : strong accent.'\u0301' : A sharp accent.'\u0302' : Circumflex accent.'\u0303' : Emphasis on tilde.'\u0308' : Umlaut accent.
When a dead key is typed, followed by another character, a dead key and the following characters are composed. For example, when the user type of dead key is a serious accent followed by the letter "a", the result is 'a'.
To get the dead key, a combination of KeyEvent.getDeadChar() , COMBINING_ACCENT and COMBINING_ACCENT_MASK . The following method is used in many open source projects to send InputConnection events to InputConnection .
private boolean translateKeyDown(int keyCode, KeyEvent event) { mMetaState = MetaKeyKeyListener.handleKeyDown(mMetaState, keyCode, event); int c = event.getUnicodeChar(MetaKeyKeyListener.getMetaState(mMetaState)); mMetaState = MetaKeyKeyListener.adjustMetaAfterKeypress(mMetaState); InputConnection ic = getCurrentInputConnection(); if (c == 0 || ic == null) { return false; } boolean dead = false; if ((c & KeyCharacterMap.COMBINING_ACCENT) != 0) { dead = true; c = c & KeyCharacterMap.COMBINING_ACCENT_MASK; } if (mComposing.length() > 0) { char accent = mComposing.charAt(mComposing.length() -1 ); int composed = KeyEvent.getDeadChar(accent, c); if (composed != 0) { c = composed; mComposing.setLength(mComposing.length()-1); } } onKey(c, null); return true; }
Another way?
@pskink mentions TextKeyListener , BaseKeyListener and KeyListener . This may be the best way. However, I could not find an adequate explanation and examples of how to use them.