Android:WebView/BaseInputConnection 中的退格键

标签 android android-input-method android-4.2-jelly-bean

我在 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/

相关文章:

android - 如何动态添加锁屏小部件

android - Webview shouldOverrideUrlLoading 适用于以前的 android 版本,除了 4.1.x jellybean

android - 如何在 Android 应用程序的选项卡上添加气泡计数器?

javascript - 使用cordova、android应用程序捕获和上传选项的不同图像路径

android - 即使连接了硬件键盘也显示软键盘

android - 如何判断输入法选择器是打开还是关闭?

android - 如何编辑错误不应该发生 : no rect-based-test nodes found

java - 如何从微调器中获取返回值的数据?

android - 如何在服务中获取 Intent?

android:windowSoftInputMode ="adjustResize"没有任何区别?