19

How to convert the keycode into char or string??

Here is the example code:

public boolean onKey(View v, int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub
    //Log.d("EditText", "It's Working...!" + event.getAction());
    if (event.getAction() == 0) {
        switch (v.getId()) {
        case R.id.editText1:
            Log.d("EditText", "In editText1");
            if (text1.length() == 3)
            {
                text2.setText();
                text2.requestFocus();

            }
            break;

        case R.id.editText2:
            Log.d("EditText", "In editText2");
            if (text2.length() == 0)
                text1.requestFocus();
            break;
        }
    }

    return false;
}
Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
ram
  • 3,487
  • 10
  • 33
  • 47

7 Answers7

54
char unicodeChar = (char)event.getUnicodeChar();
Tod
  • 4,618
  • 4
  • 32
  • 23
  • Why I got �� when I input keyevent 67 (KEYCODE_DEL) ? – Corey Apr 16 '18 at 05:36
  • if you get output like this ��. Filter it this way if (keyCode != 59) – Azizi Musa Jul 02 '19 at 08:41
  • Note that you don't need to have `KeyEvent` reference to do this. You can convert plain keycode int value by using `KeyCharacterMap`. This is atm basically what `getUnicodeChar()` does. – Peter Sep 27 '20 at 22:14
  • getUnicodeChar() now requieres a parameter, that code doesn't work like that – Windgate Oct 15 '21 at 10:26
6

Use event.getNumber().

Dave
  • 6,064
  • 4
  • 31
  • 38
3

If you don't have a KeyEvent object you can use this on the keycode :

public void onKey(int primaryCode, int[] keyCodes) {
     char c = Character.toChars(primaryCode)[0];
}
Raffy
  • 79
  • 4
2

Tod answer is almost complete, but when you want to settext of an edittext with this eventcode you should to add a little thing:

sample_et.setText((char)event.getUnicodeChar()+"");
saleh sereshki
  • 2,402
  • 3
  • 17
  • 18
0

If you want to send a key from one control to another (for instance, from RecylerView to EditText inside it), you can use this:

editText.dispatchKeyEvent(KeyEvent(0, 0, KeyEvent.ACTION_DOWN, keyCode, 0))
editText.dispatchKeyEvent(KeyEvent(0, 0, KeyEvent.ACTION_UP, keyCode, 0))
CoolMind
  • 26,736
  • 15
  • 188
  • 224
-3

Try this..

String s="";

@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
    EditText t=(EditText)v;
    s=t.getText();  
    return false;
}
Hermann Hans
  • 1,798
  • 1
  • 13
  • 24
-3

Use

String.fromCharCode();

String.fromCharCode(65,66,67) returns ABC.

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/fromCharCode .

kipid
  • 585
  • 1
  • 8
  • 19