Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

On Android webview when i execute javascript the sotfkeyboard disappear

In WebView when I execute a JavaScript through webview.loadUrl(), the softkeyboard disappears if it is visible. When I try to type some text in html text field, the softkeyboard disappears (if JavaScript is executed) and I'm unable to type the all text.

The text field does not lose focus, so the prompt is still on the text field, but the softkeyboard goes down.

Can someone tell me how fix that?

like image 967
Luciano Salemme Avatar asked Oct 24 '12 13:10

Luciano Salemme


2 Answers

The easiest way of doing that is storing the javascript calls in a plugin or a JavascriptInterface and have repeating method in your javascript side executing it. That way loadUrl is never called.

Something like:

StringBuilder sb = null;
private final Object LOCK = new Object();
public void sendJavascript(String js){
  synchronized(LOCK) {
  if (sb == null){
     sb = new StringBuilder();
     sb.append("javascript:");
  }
   sb.append(js):    
  }  
}

Then using a javascriptInterface:

private class JsInterface  {


@JavascriptInterface
    public String getJavascript(){
       synchronized(LOCK) {
        String javascriptToRun = sb.toString();
        sb = new StringBuilder();
        sb.append("javascript:");
        return javascriptToRun;
        }
      }
 }

Add your javascript interface to your webview:

JsInterface  jsInterface = new JavascriptInterface();
webview.addJavascriptInterface(jsInterface, "JsInterface");

And on your javascript code set a timed interval for retrieving the stored function.

EDIT

I just found this answer, it shows mine has a big problem, the methods are not synchronized. Meaning when you call getJavascript() our variable sb might not be ready to be read yet. I've added the relevant bit to the source above.

USE THE LOCKS or your code will be unreliable

like image 160
caiocpricci2 Avatar answered Nov 02 '22 12:11

caiocpricci2


That is an expected behavior: by calling WebView.loadUrl() you are basically reloading the page, hence soft keyboard is dismissed.

Alternatively, you may try to determine if soft keyboard is shown and delay JS execution until it is hidden. For a general method to check the soft keyboard status, see How to check visibility of software keyboard in Android?

like image 42
ozbek Avatar answered Nov 02 '22 11:11

ozbek