Translated from the original: Close / hide the keyboard on the Android screen
You can force to hide the virtual keyboard using the class InputMethodManager
,
calling the hideSoftInputFromWindow
method, sending the token of the window that contains the focused view.
// Compruebe si ninguna vista tiene el foco.
View view = this.getCurrentFocus();
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
This will force the keyboard to hide in all situations. In some cases you will have to pass InputMethodManager.HIDE_IMPLICIT_ONLY
as the second parameter to ensure that only the keyboard is hidden when the user does not explicitly force it to appear (by pressing and holding the menu).
However, since Android 4.1+
, you have to add view.clearFocus()
to work correctly:
View view = this.getCurrentFocus();
view.clearFocus()
if (view != null) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}