我编辑了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);
}
}
在我的应用程序中,我有一个我在this thread之后设置的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)
最后一个日志语句始终生成null。