Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a character into keycode

Tags:

android

I have a character and I want to convert it into KeyEvent KeyCode constraints http://developer.android.com/reference/android/view/KeyEvent.html#KEYCODE_0

Like if I have a character '0' I wan to convert into

Key code constant: '0' key.

Constant Value: 7 (0x00000007)

as specified in the KeyEvent page. What can be a best method for doing this? Is there any predefined function to do it?

like image 364
dead programmer Avatar asked Sep 06 '13 14:09

dead programmer


People also ask

What is e keycode === 13?

Keycode 13 is the Enter key.

What is the difference between keycode and charCode?

keyCode: Returns the Unicode value of a non-character key in a keypress event or any key in any other type of keyboard event. event. charCode: Returns the Unicode value of a character key pressed during a keypress event.


3 Answers

I'm still new to Java/Android, so my answer may not work out of the box, but you may still get the idea.

import android.view.KeyCharacterMap;
import android.view.KeyEvent;    
...
public class Sample {
    ...
    public boolean convertStringToKeyCode(String text) {

        KeyCharacterMap mKeyCharacterMap = 
            KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);

        KeyEvent[] events = mKeyCharacterMap.getEvents(text.toCharArray());

        for (KeyEvent event2 : events) {
            // We get key events for both UP and DOWN actions,
            // so we may just need one.
            if (event2.getAction() == 0) {
                int keycode = event2.getKeyCode();
                // Do some work
            }
        }
}

I got the idea when I was reading the code of sendText method in uiautomator framework source code:

like image 103
Hieu Avatar answered Oct 15 '22 07:10

Hieu


Here is a solution I use to put chars in a webview:

char[] szRes = szStringText.toCharArray(); // Convert String to Char array

KeyCharacterMap CharMap;
if(Build.VERSION.SDK_INT >= 11) // My soft runs until API 5
    CharMap = KeyCharacterMap.load(KeyCharacterMap.VIRTUAL_KEYBOARD);
else
    CharMap = KeyCharacterMap.load(KeyCharacterMap.ALPHA);

KeyEvent[] events = CharMap.getEvents(szRes);

for(int i=0; i<events.length; i++)
    MainWebView.dispatchKeyEvent(events[i]); // MainWebView is webview
like image 27
Philippe Mignard Avatar answered Oct 15 '22 07:10

Philippe Mignard


Very rude solution but works for most characters.

Remember to do an uppercase if your text contains lowercase letters, you can add META_SHIFT_ON in that case if you then send a KeyEvent

    for (int i = 0; i < text.length(); i++) {
        final char ch = text.charAt(i);
        try {
            dispatch(KeyEvent.class.getField("KEYCODE_" + ch).getInt(null));
        } catch (Exception e) {
            Log.e(_TAG, "Unknown keycode for " + ch);
        }
    }
like image 45
Gianluca P. Avatar answered Oct 15 '22 09:10

Gianluca P.