2

我是 Android 开发新手,目前正在为 Google Android 操作系统(API 级别 11 == 3.0 版)编写输入法编辑器 (IME)。

(以下代码被简化以指出问题。)

我可以通过以下方式将字符发送到底层应用程序:

@Override
public final void onKey(final int primaryCode, final int[] keyCodes) {    
    this.getCurrentInputConnection().commitText(String.valueOf((char) primaryCode), 1);
}

现在我想发送特殊的组合键(例如 SHIFT + A)。达到此目标的 Java 代码如下(针对 SHIFT + A 的特殊情况):

@Override
public final void onKey(final int primaryCode, final int[] keyCodes) {
        long eventTime = SystemClock.uptimeMillis();    
        this.sendDownKeyEvent(KeyEvent.KEYCODE_SHIFT_LEFT);

        KeyEvent keyEvent = new KeyEvent(
            eventTime,
            eventTime,
            KeyEvent.ACTION_DOWN,
            KeyEvent.KEYCODE_A, // ToDo: How to convert primaryCode to the corresponding KeyEvent constant?
            KeyEvent.META_SHIFT_ON
        );
        this.getCurrentInputConnection().sendKeyEvent(keyEvent);
}

public final void sendDownKeyEvent(final int keyEventCode) {
    InputConnection ic = this.getCurrentInputConnection();
    if (ic != null) {
        long eventTime = SystemClock.uptimeMillis();
        ic.sendKeyEvent(
            new KeyEvent(
                eventTime, eventTime,
                KeyEvent.ACTION_DOWN, keyEventCode, 0, 0, 0, 0,
                KeyEvent.FLAG_SOFT_KEYBOARD | KeyEvent.FLAG_KEEP_TOUCH_MODE
            )
        );
    }
}

上一个代码示例中的注释显示了我的问题。要通过KeyEvent对象发送组合键,我必须将变量primaryCode(包含按下的键的 unicode 代码)转换为KeyEvent类的常量。

这种情况下的方便方法是否已经存在,还是我必须自己编写?一般来说:上述发送键组合的解决方案是优雅的还是存在更好的方法?(在互联网上很难找到 Android IME 的示例......)

先感谢您!

4

1 回答 1

1

好像有点晚了。我找到了针对同一问题的以下解决方案,将 aprimaryCode转换为KeyEvents.

该解决方案涉及加载 aKeyCharacterMap并使用其KeyCharacterMap.getEvents()方法获取可以重现字符的 KeyEvent 列表。

//This snippet tries to translate the glyph 'primaryCode' into key events

//retrieve the keycharacter map from a keyEvent (build yourself a default event if needed)
KeyCharacterMap myMap=KeyCharacterMap.load(event.getDeviceId()); 

//event list to reproduce glyph
KeyEvent evs[]=null;

//put the primariCode into an array
char chars[]=new char[1];
chars[0]=primaryCode;

// retrieve the key events that could have produced this glyph
evs=myMap.getEvents(chars);

if (evs != null){
    // we can reproduce this glyph with this key event array
    for (int i=0; i< evs.length;i++) MySendKeyEventHelperMethod(evs[i]);
}
else { /* could not find a way to reproduce this glyph */ }
于 2011-11-01T18:49:33.013 回答