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

Viewed 27328

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;
}
7 Answers

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];
}

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()+"");

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))
Related