How can I open and close the virtual keyboard (soft-keyboard)?

18

I want to show the virtual keyboard (soft-keyboard) for some EditText that has focus and that has been obtained programmatically (without having been pressed). And close it when an event occurs such as pressing a Button on the screen.

    
asked by raukodraug 03.12.2015 в 00:05
source

2 answers

7

To show 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 it is necessary that another View 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);
    
answered by 03.12.2015 / 00:05
source
7

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);
}
    
answered by 03.12.2015 в 00:23