简体   繁体   中英

How to determine when an HTML element gains focus in Android WebView?

I am trying to determine when a Text Field in a html page is focused from the Android WebView. Some notes: I do not own the web page so I can't add anything directly to the webpage.

What I have tried:

    webSettings.setJavaScriptEnabled(true);
    webSettings.setDomStorageEnabled(true);
    webView.addJavascriptInterface(new Object() {

        @JavascriptInterface
        public void displayScanButton() {
            WebViewActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.d("SCAN", "DISPLAY SCAN BUTTON");
                    toolbar.setVisibility(View.VISIBLE);
                }
            });
        }

        @JavascriptInterface
        public void hideScanButton() {
            WebViewActivity.this.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.d("SCAN", "HIDE SCAN BUTTON");
                    toolbar.setVisibility(View.GONE);
                }
            });
        }
    }, "Android");

@Override
public void onPageFinished(WebView view, String url) {
    view.loadUrl("javascript:document.getElementById('tNewLabels').onfocus = Android.displayScanButton; document.getElementById('tNewLabels').onfocusout = Android.hideScanButton;");
}

I have a couple variations of that as well but that is what I currently have. It does not set onfocus for the input field.

Basically what I want is when the user clicks on the input field to type in text, I display my toolbar that I have attached to the keyboard for this specific element only. And when the user no longer has focus of the input field, hide the toolbar. I would think there would be a way since the WebView knows when to open up the keyboard and when to close it. Possibly a way to intercept this?

Thanks for any help.

Try this:

document.getElementById('tNewLabels').onfocus = function() { Android.displayScanButton(); };
document.getElementById('tNewLabels').onfocusout = function() { Android.hideScanButton(); };

For the Android-Java bridge to work, your function must have the interface object as the "this" variable. Assigning the function directly to the event strips it from its attachment to the interface object. I heard it used to work anyway in older versions of the WebView, but it no longer does.

And sorry for reviving an old question, you probably have already figured it out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM