Read Keyboard events in Android WebView

前端 未结 4 2196
旧时难觅i
旧时难觅i 2020-12-15 09:23

I\'m trying to listen to key events in android web view. Example when user is filling a form, I should receive the key events. This is my WebView code

public         


        
相关标签:
4条回答
  • 2020-12-15 09:48

    you can use javascript like this

    <body>
        
        <div contenteditable="true" id='box'></div>
    </body>
        <script>
            box.addEventListener('keydown',e=>{
                if(e.keyCode ===13){
                    alert('pressed enter key')
                }
            })
        </script>

    0 讨论(0)
  • 2020-12-15 10:03

    I don't know if you tried this already but...alternatively, you can enable javascript for your "MyWebViewClass" and use javascript events to call java code using webView.addJavascriptInterface(....etc)

    Full Story :- http://developer.android.com/guide/webapps/webview.html#BindingJavaScript

    0 讨论(0)
  • 2020-12-15 10:09

    You can use onUnhandledKeyEvent() function overrid on WebViewClient class. Works perfectly for me.

    onUnhandledKeyEvent

    @Override
    public void onUnhandledKeyEvent(WebView view, KeyEvent event) {
          return;
    }
    
    whenever a user presses any key on the keyboard, this event will get fire.
    Please let me know if that's works for you?
    
    0 讨论(0)
  • 2020-12-15 10:11

    Caution! This solution supports only English letters.

    Accomplished without any access to the HTML source code or JS events. Works for me on Android 5.0.2 for both soft and hardware keyboards.

    public class MyWebView extends WebView {
    
    
        @Override
        public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
            return new BaseInputConnection(this, false); //this is needed for #dispatchKeyEvent() to be notified.
        }
    
        @Override
        public boolean dispatchKeyEvent(KeyEvent event) {
            boolean dispatchFirst = super.dispatchKeyEvent(event);
            // Listening here for whatever key events you need
            if (event.getAction() == KeyEvent.ACTION_UP)
                switch (event.getKeyCode()) {
                    case KeyEvent.KEYCODE_SPACE:
                    case KeyEvent.KEYCODE_ENTER:
                        // e.g. get space and enter events here
                        break;
                }
            return dispatchFirst;
        }
    }
    

    The trick here is overriding the system-provided input implementation of InputConnection with a simplified one. Preventing developers from accessing the events by default was made by Googlers on purpose. Because the key event input isn't the only one anymore. There're gestures, voice and more is coming. Official recommendation is to "stop relying on legacy key events for text entry at all". Check out more details here: https://code.google.com/p/android/issues/detail?id=42904#c15

    0 讨论(0)
提交回复
热议问题