7

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?

Kyle Falconer
  • 7,586
  • 5
  • 44
  • 63
Luciano Salemme
  • 287
  • 2
  • 14
  • Maby a messy solution, you could try to "force" the keyboard to be visible (google it) or check the keyboard state, and if the state is "not visible" you could set the keyboard to visible. Don't know if it works, just an idea. – Mdlc Jul 04 '13 at 16:31

2 Answers2

5

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

Community
  • 1
  • 1
caiocpricci2
  • 7,514
  • 10
  • 50
  • 86
1

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?

Community
  • 1
  • 1
ozbek
  • 20,085
  • 5
  • 54
  • 79