Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - How to convert KeyEvent KeyCode to Char? [duplicate]

Tags:

android

I want to get the char value of the KeyCode Event when pressing an Android keyboard.

public void KeyCodeEventAsChar(int keyCode, KeyEvent event) {

  char pressedKey;

  // TODO: convert key Code Event into char

  syslog.d ("TEST", "The pressed key in Android keyboard was char: " + pressedKey);

}

Does anyone has a clue how to do this?!

UPDATE:

I don't want hardcoded text! I want to convert it to correspondent char!

UPDATE 2:

I need also to dead chars such as: à, á, ò, ó, etc...

ANSWER FOUND:

// TODO: convert key Code Event into char
char pressedKey = (char) event.getUnicodeChar();

IMPORTANT NOTE: char has only 1 byte length, so it will not support several chars

like image 716
Jorge Avatar asked May 16 '12 12:05

Jorge


4 Answers

> I had already answered updating the question

// TODO: convert key Code Event into char
char pressedKey = (char) event.getUnicodeChar();

IMPORTANT NOTE: char has only 1 byte length, so it will not support several chars

Hope it help you somehow

like image 176
Jorge Avatar answered Nov 18 '22 23:11

Jorge


You can use KeyEvent.getDisplayLabel() to get the primary character for the key. In other words, the label that is physically printed on it.

like image 35
Diego Torres Milano Avatar answered Nov 18 '22 23:11

Diego Torres Milano


In order to test the Answer Found you can do this:

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {

    char pressedKey = (char) event.getUnicodeChar();

    Log.d("onKeyUp is: ", Character.toString(pressedKey));


    return super.onKeyUp(keyCode, event);

}

And the letter that you pressed should appear in the logcat

like image 3
Maduro Avatar answered Nov 19 '22 00:11

Maduro


You have to check which key is getting pressed like this

if(keyCode  == KeyEvent.KEYCODE_ENTER){

syslog.d ("TEST", "The pressed key in Android keyboard was Enter" );
}

Here is the link where you find all the KeyEvents

http://developer.android.com/reference/android/view/KeyEvent.html

like image 1
Sachin Gurnani Avatar answered Nov 18 '22 22:11

Sachin Gurnani