3

我编辑了 SoftKeyboard IME Android 示例代码以将自定义 KeyEvent 传递给我的应用程序。我使用这个KeyEvent Constructor来做到这一点:

private void handleCharacter(int primaryCode, int[] keyCodes) {
  if (isInputViewShown()) {
    if (mInputView.isShifted()) {
      primaryCode = Character.toUpperCase(primaryCode);
    }
  }
  if (isAlphabet(primaryCode)) {
    String characterString = new String();
    for (int c : keyCodes) {
      characterString += (char)c;
    }
  Log.e(TAG, "sending: " + characterString);
  KeyEvent ke = new KeyEvent(SystemClock.uptimeMillis(),
      characterString, 0, KeyEvent.FLAG_CANCELED);
  getCurrentInputConnection().sendKeyEvent(ke);
  }
}

在我的应用程序中,我有一个 CustomTextView,我在这个线程之后设置了,我写了onKey()这样的:

@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
  Log.d(TAG, "onKeyListener");
  CustomEditor context = (CustomEditor) mWeakContext.get();
  assertNotNull("Context invalid", context);

  if (event.getAction() == KeyEvent.ACTION_UP) {
    if (keyCode == KeyEvent.KEYCODE_DELETE) {
      // Handle delete.
      return true;
    }

    if (keyCode == KeyEvent.KEYCODE_SPACE) {
      // Handle space.
      return true;
    }
  }

  // Ignore all non-custom Events.
  if (event.getAction() != KeyEvent.ACTION_MULTIPLE) {
    return true;
  }

  if (keyCode == KeyEvent.KEYCODE_UNKNOWN) {
    Log.e(TAG, event.toString());
    // Pull out characters.
    final String chars = event.getCharacters();
    if (chars != null) {
      // Do some stuff. This is never called!
    }
  }
  return true;
}

但是event.getCharacters()永远不会返回非空字符串!这里有什么我想念的吗?没有太多的文档来管理我试图操纵这个特定的 KeyEvent 构造函数来达到我自己的目的。

编辑: KeyEvent.writeToParcel(...) 函数似乎没有打包字符串,因此当 KeyEvent 发送到 TextView 时数据会丢失。

我尝试对以这种方式构造的 KeyEvent 进行编组和解组,实际上该字符串不再存在。这种行为很奇怪。有人知道为什么吗?

...
KeyEvent ke = new KeyEvent(SystemClock.uptimeMillis(),
      characterString, 0, KeyEvent.FLAG_CANCELED);
// Drop it into a parcel
Parcel p = Parcel.obtain();
ke.writeToParcel(p, 0);
// Get it out of this parcel.
KeyEvent kee = KeyEvent.CREATOR.createFromParcel(p);
Log.e(TAG, "unparcelled cstring: " + kee.getCharacters());
... (etc)

最后一条日志语句总是产生空值。

4

0 回答 0