Android:在WebView / BaseInputConnection中退格

Android(4.2)中的软键盘退格有问题。

我在WebView(CodeMirror)中有一个自定义编辑器,它在内部使用一个空的<textarea> 。 看起来backspace不是由Android系统发送的,除非它认为<textarea>有一些文本。

我已经重写了WebView onCreateInputConnection ,试图减弱软input:

 @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不会被称为退格。

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

Solutions Collecting From Web of "Android:在WebView / BaseInputConnection中退格"

好的,终于明白了这一点。

在Android 4.2中(也许在早期版本中),退格不会作为sendKeyEvent(..., KeyEvent.KEYCODE_DEL)被标准软键盘发送。 而是将其作为deleteSurroundingText(1, 0)

所以在我的情况下,解决scheme是使用下面的自定义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写的。

这个代码会更好,它使用更多的键盘: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) ; } }