How To Disable Soft keyboard in Android WebView

haomin
haomin
Aug 14 · 2 min read

You could take into consideration of an approach from both Javascript and Android combined.

Below is how to achieve hiding:

First on Javascript side

We can create a JS file to handle the webpage displayed in the WebView, and apply it to the webview by calling this in the onCreate of the MainActivity i.e:

@Override
protected void onCreate(Bundle savedInstanceState) {
/*
Normal onCreate stuff
*/
ExtendedWebView webView = findViewById(R.id.webview_id);
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
webView.addJavascriptInterface(new MyJavascript(), "_my_javascript");
}

Second: on Java side

Now that we have the JS part taken care of, we need to extend the WebView we are using to override a specific method provided by the WebView class from the framework:

@Override 
public InputConnection onCreateInputConnection(EditorInfo outAttrs) {
hideKeyboard();
return super.onCreateInputConnection(outAttrs);
}

What this method does is to create an input connected to the input_box in the HTML webpage displayed in webview, and this method is called the first time you click an input box on the webview. However, this method will only be called once before the input connection is established, which means if you call hideKeyboard() in this method, it will only work the first time user clicks it, but not the second time.

BUT, together with the JS change we have earlier, hideKeyboard() will work… How?

Since in the JS file we created earlier we forced the onClick of the input box to trigger a blur() call, which closes the current input connection, and followed by a focus() call to let android focus on to the same input_box again, allowing user to interact with the input box without the soft keyboard popping out, which successfully answered this question: Disable SoftKeyboard inside a WebView

private void hideKeyboard() {
post(new Runnable() {
@Override
public void run() {
InputMethodManager imm = (InputMethodManager) getContext()
.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) imm.hideSoftInputFromWindow(getRootView().getWindowToken(), 0);
}
});
}

Source: I worked on a device with hardware num keys, but has no physical qwerty keyboard, and found out this solution when trying to disable soft keyboard popping out only when input box type is limited to numbers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade