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?
Keycode 13 is the Enter key.
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.
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:
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
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);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With