How can I convert a key code into a char or string?
Asked Answered
S

7

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;
}
Sliding answered 4/7, 2011 at 11:50 Comment(0)
R
54
char unicodeChar = (char)event.getUnicodeChar();
Ramakrishna answered 11/2, 2012 at 0:35 Comment(4)
Why I got �� when I input keyevent 67 (KEYCODE_DEL) ?Lampkin
if you get output like this ��. Filter it this way if (keyCode != 59)Norvan
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.Factorize
getUnicodeChar() now requieres a parameter, that code doesn't work like thatPostdiluvian
K
6

Use event.getNumber().

Kherson answered 4/7, 2011 at 12:28 Comment(0)
P
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];
}
Piroshki answered 27/11, 2013 at 22:55 Comment(0)
S
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()+"");
Swagger answered 26/6, 2018 at 14:10 Comment(0)
M
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))
Monoculture answered 1/7, 2021 at 12:45 Comment(0)
V
-3

Try this..

String s="";

@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
    EditText t=(EditText)v;
    s=t.getText();  
    return false;
}
Vomiturition answered 6/12, 2012 at 7:51 Comment(0)
G
-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 .

Grecism answered 24/6, 2014 at 4:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.