How to detect when an HTML element is receiving focus in an Android WebView?

I am trying to detect when a textbox in a html page is targeting Android WebView. Some notes: I don't have a webpage, so I cannot 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 several options for this, but this is what I have. It doesn't set onfocus for the input field.

Basically what I want is when the user clicks on an input field to enter text, I show my toolbar, which I have bound to the keyboard for that specific element only. And when the user no longer has the focus of the input field, hide the toolbar. I would have thought that since the WebView knows when to open the keyboard and when to close it, there would be a way to go. Perhaps this is a way to intercept this?

Thanks for any help.

+3


source to share


1 answer


Try the following:

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

      



For Android-Java modem to work, your function must have an interface object as the "this" variable. Assigning a function directly to an event breaks it down into binding to the interface object. I heard it worked anyway in older versions of WebView, but it doesn't work anymore.

And sorry for reviving the old question, you probably already figured that out.

0


source







All Articles