How can I open and close the virtual keyboard (soft-keyboard)?
I want to display the virtual keyboard (soft-keyboard) for some EditText
that has focus and that has been obtained programmatically (without being pressed). And close it when some event occurs like pressing a Button
on the screen.
3 answers
To display the virtual keyboard (soft-keyboard) forcibly, you can use:
EditText editText= (EditText) findViewById(R.id.editText);
editText.requestFocus(); //Asegurar que editText tiene focus
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT);
However, if you want to remove the focus from editText
you need another View
to get the focus. So if you do not have another View
you will have to create another View
empty and give the focus to it.
To close the virtual keyboard, you can use:
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(yourEditText.getWindowToken(), 0);
Translated from the original: close / hide Android on-screen keyboard
You can force to hide the virtual keyboard using the Class InputMethodManager
,
calling the hideSoftInputFromWindow
method, sending the token from the window containing 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 a second parameter to ensure that the keyboard is only hidden when the user does not force explicitly appear (holding down menu).
However from Android 4.1+
, you have to add view.clearFocus()
for it 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);
}
In Kotlin I worked the following in case they need it, they use the corresponding between the activity or the fragment depending on where they want to make the call
fun YourFragmentName.hideKeyboard() {
view?.let { activity?.hideKeyboard(it) }
}
fun YoActivityName.hideKeyboard() {
hideKeyboard(currentFocus ?: View(this))
}
fun Context.hideKeyboard(view: View) {
val inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}
Example of use in a fragment:
view.btn_login.setOnClickListener {
hideKeyboard()
}