How to show/hide the Android soft keyboard programmatically?
Photo by Emojisprout on Unsplash |
You can force Android to close or hide the virtual keyboard using the
InputMethodManager
calling and passing in the token of
the window containing your focused view.Similarly, you can show the virtual keyboard using the
InputMethodManager
calling showSoftInput
and
passing your focused view and flag.
// hide keyboard fun dismissKeyboard(view: View?) { if (view != null) { val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(view.windowToken, 0) } } // show keyboard fun showKeyboard(view: View?) { if (view == null) return view.requestFocus() val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager if (view is EditText) imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT) else imm.toggleSoftInput( InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY ) }
This will force the keyboard to be hidden in all situations. In some
cases, you will want to pass in
InputMethodManager.HIDE_IMPLICIT_ONLY
as the second parameter to ensure you only hide the keyboard when the
user didn’t explicitly force it to appear (by holding down the menu).
WindowSoftInputMode
By default, Android will automatically assign the initial focus to the
first
EditText
or focusable control in your Activity. It naturally
follows that the InputMethod
(typically the soft keyboard) will
respond to the focus event by showing itself. The windowSoftInputMode
attribute in AndroidManifest.xml
, when set to stateAlwaysHidden
,
instructs the keyboard to ignore this automatically-assigned initial
focus.
<activity android:name=".MainActivity" android:windowSoftInputMode="stateAlwaysHidden"/>