15

我在 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不需要退格。

如何强制软键盘始终发送退格键?

4

2 回答 2

34

好的,终于想通了。

在 Android 4.2(可能在早期版本中也是如此)中,退格键不是sendKeyEvent(..., KeyEvent.KEYCODE_DEL)由标准软键盘作为 a 发送的。相反,它以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 写作的第三天。

于 2013-01-28T11:47:01.690 回答
2

这段代码会更好,它适用于更多键盘:D

@Override
  public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
      outAttrs.actionLabel = null;
      outAttrs.inputType = InputType.TYPE_NULL;
      final InputConnection con = new BaseInputConnection(this,false);
      InputConnectionWrapper public_con = new InputConnectionWrapper(
              super.onCreateInputConnection(outAttrs), true) {
          @Override
          public boolean deleteSurroundingText(int beforeLength, int afterLength) {
              if (beforeLength == 1 && afterLength == 0) {
                  return this.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL))
                          && this.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_DEL));
              }
              return super.deleteSurroundingText(beforeLength, afterLength);
          }

          @Override
          public boolean sendKeyEvent(KeyEvent event) {
              if(event.getKeyCode() == KeyEvent.KEYCODE_DEL){
                  return con.sendKeyEvent(event);
              }else {
                  return super.sendKeyEvent(event);
              }
          }
      };
      try {
          return public_con ;
      }catch (Exception e){
          return super.onCreateInputConnection(outAttrs) ;
      }
  }
于 2016-10-27T06:09:23.437 回答