我在 Android (4.2) 中遇到了软键盘退格问题。
我在 WebView (CodeMirror) 中有一个自定义编辑器,它使用一个空的 <textarea>
内部。似乎退格不是由 Android 系统发送的,除非它认为 <textarea>
中有一些文本。 .
我已覆盖 WebView
onCreateInputConnection
试图降低软输入:
@Override
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
Log.d("CustomWebView", "onCreateInputConnection(...)");
BaseInputConnection connection = new BaseInputConnection(this, false);
outAttrs.inputType = InputType.TYPE_NULL;
outAttrs.imeOptions = EditorInfo.IME_ACTION_NONE;
outAttrs.initialSelStart = -1;
outAttrs.initialSelEnd = -1;
return connection;
}
但是,这不起作用,甚至 onKeyUp
不需要退格。
如何强制软键盘始终发送退格键?
最佳答案
好的,终于明白了。
在 Android 4.2(可能还有早期版本)中,退格键不是由标准软键盘作为 sendKeyEvent(..., KeyEvent.KEYCODE_DEL)
发送的。相反,它作为 deleteSurroundingText(1, 0)
发送。
因此,在我的情况下,解决方案是使用以下内容制作自定义 InputConnection
:
@Override
public boolean deleteSurroundingText(int beforeLength, int afterLength) {
// magic: in latest Android, deleteSurroundingText(1, 0) will be called for backspace
if (beforeLength == 1 && afterLength == 0) {
// backspace
return super.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
&& super.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL));
}
return super.deleteSurroundingText(beforeLength, afterLength);
}
注意:如果我在这里做一些愚蠢的事情,请告诉我,因为这是我为 Android 编写的第三天。
关于Android:WebView/BaseInputConnection 中的退格键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14560344/