在Android WebVIew中,长按键盘按键并不会像普通的View那样触发长按事件。为了处理长按按键事件,需要通过JS注入的方式来在前端代码中处理。具体步骤如下:
WebChromeClient mWebChromeClient = new WebChromeClient() { @Override public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) { WebView newWebView = new WebView(context); // 设置JS交互 newWebView.getSettings().setJavaScriptEnabled(true); view.addView(newWebView); WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj; transport.setWebView(newWebView); resultMsg.sendToTarget(); return true; } };
String js = "var tag = document.getElementsByTagName('input'); " + "for (var i = 0; i < tag.length; i++) { " + " tag[i].addEventListener('keydown', " + " function(event) { " + " event.preventDefault(); " + " var code = event.keyCode; " + " var ele = this; " + " var timeId = setTimeout(function() { " + " ele.dispatchEvent(new KeyboardEvent('long-key-press', {keyCode: code})); " + " }, 1500); " + " this.addEventListener('keyup', function() { " + " clearTimeout(timeId); " + " }); " + " }); " + "}";
newWebView.setWebChromeClient(new WebChromeClient() { @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { if (message.startsWith("long-key-press")) { int keyCode = Integer.parseInt