【问题标题】:Backspace key Events not fired on Android 4.1+ webview退格键事件未在 Android 4.1+ webview 上触发
【发布时间】:2014-04-30 03:34:39
【问题描述】:

在webview或默认浏览器中,只有当输入不为空时,我才能接收退格键事件(keyup,keydown和keypress),这似乎是android 4.1+的错误。

你可以试试下面这个页面(用安卓设备打开) http://javascript.info/tutorial/keyboard-events#test-stand-test-stand

我通过创建自定义 InputConnection 尝试了答案 herehere

现在可以了,即使输入为空也可以接收退格键事件,但是有副作用:

我不能再输入单词和短语了(第一和第二张图片),

我一次只能输入一个字母或字符(第三张图片)。

我该如何解决这个问题,有什么解决方法吗?谢谢。

【问题讨论】:

    标签: android webview backspace


    【解决方案1】:

    我不知道你的情况,但在我的情况下,qwerty 键盘有退格键按下/键上事件,但数字没有触发退格键事件,我的 android 版本是 4.4.2 我已经修改了你提到的那 2 篇文章中使用的代码。只需使用此代码,您的退格键事件就会被触发

    这是我们定义自己的 onCreateInputConnection 的扩展 webview 类 ExtenderInputConnection 是我的类,它扩展了基本输入连接,它的代码也在下面给出

    @Override
    public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
        super.onCreateInputConnection(outAttrs);
        //This Code is for showing Decimal point in numeric Keyboard
        if ((outAttrs.inputType & InputType.TYPE_CLASS_NUMBER) == InputType.TYPE_CLASS_NUMBER)
        {
            outAttrs.inputType |= InputType.TYPE_NUMBER_FLAG_DECIMAL;
        }
        else
        {
            InputConnection connection = super.onCreateInputConnection(outAttrs);
            return connection;
        }
         return new ExtenderInputConnection(this,false);
    }
    

    这是 ExtenderInputConnection 的代码

    import android.text.InputType;
    import android.view.KeyEvent;
    import android.view.View;
    import android.view.inputmethod.BaseInputConnection;
    import android.view.inputmethod.EditorInfo;
    import android.view.inputmethod.InputConnection;
    
    public class ExtenderInputConnection extends BaseInputConnection implements InputConnection{
    
    public ExtenderInputConnection(View targetView, boolean fullEditor) {
        super(targetView, fullEditor);
        // TODO Auto-generated constructor stub
    }
    
    @Override
    public boolean deleteSurroundingText(int beforeLength, int afterLength) {       
        if (beforeLength == 1 && afterLength == 0) {
            // backspace
            return super.sendKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_DEL));
        }
    
        return super.deleteSurroundingText(beforeLength, afterLength);
        }
    }
    

    【讨论】:

    • 这为我修复了 Go vs Next 按钮,但是它破坏了数字输入的 Next 按钮。有什么想法吗?
    【解决方案2】:

    你需要使用 onkeyup/keydown/keypress 事件吗?它们不太适合移动输入模型,这就是存在这些错误的原因。组合事件会是您更好的解决方案吗[1]?

    [1]https://developer.mozilla.org/en-US/docs/Web/API/CompositionEvent

    【讨论】:

    • 感谢您的 anwser。我已经使用我的 android 手机在此页面中尝试了 compositionEvents,但没有触发复合事件。 jsfiddle.net/A6Ctj/5
    猜你喜欢
    • 1970-01-01
    • 2015-07-25
    • 2017-04-12
    • 2019-05-09
    • 2011-02-24
    • 1970-01-01
    • 2022-08-02
    • 2017-05-09
    • 1970-01-01
    相关资源
    最近更新 更多