Reputation: 4365
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?
Upvotes: 13
Views: 9321
Reputation: 255
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
Upvotes: 14
Reputation: 1551
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);
}
}
Upvotes: 4
Reputation: 7674
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:
Upvotes: 7
Reputation: 6610
No, you cannot read a character "0" from the input and use a magical function to transform that to KeyEvent.KEYCODE_0 ... If you do, you will have to write a parser that switches on the read letter and return these values yourself.
For all I know, before reading the character you should've captured the thing in the onKey()
. Depending on the number of keys you need to handle this way, a virtual android keyboard might be your only option, if this boilerplate code doesn't do the trick
switch(keyPress)
{
case '0': return KeyEvent.KEYCODE_0;
case '1': return ...
//...
case 'Z': return KeyEvent.KEYCODE_Z;
}
Upvotes: 2