Android: Force Hide System Keyboard While Retaining EditText’s Focus

CHEN SU
CS Random Thoughts on Tech
3 min readJan 2, 2018

There are cases that you want more controls on custom IME in your application, for example, like the WolframAlpha, having a switch in Settings to turn on/off your custom keyboard.

WolframAlpha’s custom IME

From what I’ve researched so far, WolframAlpha doesn’t register their IME as a system IME, which means you cannot find its keyboard in OS Settings. They limit their custom keyboard just within their app, and they show it based on a switch in the app Settings(“Use custom keyboard”).

My guess of their implementation is that they’ve created a view for custom keyboard, and programmatically set its visibility based on the SharedPreference of “Use custom keyboard”, when the EditText gets focus.

There is one important point for this implementation is that when EditText gets focus, they need to force hide the system keyboard if the setting is on. Otherwise, 2 keyboards will show up, one system and one custom.

So the requirement is how to force hide system keyboard while remaining the focus in EditText.

I’ve searched a lot and people are recommending this:

Use InputMethodManager to hide system keyboard

However, this won’t work for this case, since the hideSofteInputFromWindow will take away the focus in EditText!

Then how do we retain the blinking cursor/caret in EditText while forcing hide the system keyboard? I found that TextView.setShowSoftInputOnFocus(false) does the job.

This API was introduced with Android 5 (API 21) in November, 2014. I’ve researched on this topic pre-Lollipop and didn’t find a perfect way that works for all devices from different manufacturers. One possible way previously was to keep calling InputMethodManager.hideSoftInputFromWindow() at multiple View level lifecycle callbacks and Activity/Fragment lifecycle callbacks. However, tests showed that this won’t work perfectly on all devices. I’ve noticed Samsung or Galaxy or Asus devices had different behaviors, especially the system keyboard jumping up and disappears quickly, which was super annoying.

With the introduction of TextView.setShowSoftInputOnFocus(false) in API 21, Google has made life much easier in this use case.

However, there’s no same support for WebView yet!

Check out my proof of concept codes on GitHub:

https://github.com/martinsuchen35/Android-Force-Hide-Soft-Keyboard

Include an EditText in the layout
Call setShowSoftInputOnFocus(false) on the EditText instance, and you’re all set!

Check out the result below, the focus retains in EditText, and selection together with context menu all work, but however hard you tried clicking, the soft keyboard just won’t show up. This is great! Now you can programmatically to make the view of custom keyboard visible. Cheers!

--

--