¿Cómo descarto el teclado cuando se presiona un botón?
¿Cómo descarto el teclado cuando se presiona un botón?
Respuestas:
¿Desea deshabilitar o descartar un teclado virtual?
Si solo desea descartarlo, puede usar las siguientes líneas de código en el botón al hacer clic en Evento
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
getActivity()) getCurrentFocus().getWindowToken()para el primer argumento hideSoftInputFromWindow(). Además, hágalo en onPause()y no onStop()si está tratando de que desaparezca cuando cambie de actividades.
La solución anterior no funciona para todos los dispositivos y, además, está usando EditText como parámetro. Esta es mi solución, solo llame a este método simple:
private void hideSoftKeyBoard() {
InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
if(imm.isAcceptingText()) { // verify if the soft keyboard is open
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
isAcceptingText()hizo esta respuesta mejor que otras
Esta es mi solucion
public static void hideKeyboard(Activity activity) {
View v = activity.getWindow().getCurrentFocus();
if (v != null) {
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
Aquí hay una solución de Kotlin (mezclando las diferentes respuestas en hilo)
Crear una función de extensión (quizás en una clase ViewHelpers común)
fun Activity.dismissKeyboard() {
val inputMethodManager = getSystemService( Context.INPUT_METHOD_SERVICE ) as InputMethodManager
if( inputMethodManager.isAcceptingText )
inputMethodManager.hideSoftInputFromWindow( this.currentFocus.windowToken, /*flags:*/ 0)
}
Luego simplemente consume usando:
// from activity
this.dismissKeyboard()
// from fragment
activity.dismissKeyboard()
La primera solución con InputMethodManager funcionó como un campeón para mí, el método getWindow (). SetSoftInputMode no funcionaba en Android 4.0.3 HTC Amaze.
@Ethan Allen, no necesitaba hacer que el texto de edición sea definitivo. ¿Tal vez está utilizando una clase interna EditText que declaró el método contenedor? Puede hacer que EditText sea una variable de clase de la Actividad. O simplemente declare un nuevo EditText dentro de la clase / método interno y use findViewById () nuevamente. Además, no descubrí que necesitaba saber qué EditText en el formulario tenía el foco. Podría elegir uno arbitrariamente y usarlo. Al igual que:
EditText myEditText= (EditText) findViewById(R.id.anyEditTextInForm);
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);
public static void hideSoftInput(Activity activity) {
try {
if (activity == null || activity.isFinishing()) return;
Window window = activity.getWindow();
if (window == null) return;
View view = window.getCurrentFocus();
//give decorView a chance
if (view == null) view = window.getDecorView();
if (view == null) return;
InputMethodManager imm = (InputMethodManager) activity.getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm == null || !imm.isActive()) return;
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
} catch (Throwable e) {
e.printStackTrace();
}
}
Esta solución asegura que oculta el teclado y que no hace nada si no se abre. Utiliza la extensión, por lo que se puede usar desde cualquier clase de Context Owner.
fun Context.dismissKeyboard() {
val imm by lazy { this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager }
val windowHeightMethod = InputMethodManager::class.java.getMethod("getInputMethodWindowVisibleHeight")
val height = windowHeightMethod.invoke(imm) as Int
if (height > 0) {
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0)
}
}
Al usar el contexto de la vista, podemos lograr el resultado deseado con los siguientes métodos de extensión en Kotlin:
/**
* Get the [InputMethodManager] using some [Context].
*/
fun Context.getInputMethodManager(): InputMethodManager {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
return getSystemService(InputMethodManager::class.java)
}
return getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
}
/**
* Dismiss soft input (keyboard) from the window using a [View] context.
*/
fun View.dismissKeyboard() = context
.getInputMethodManager()
.hideSoftInputFromWindow(
windowToken
, 0
)
Una vez que estén en su lugar, solo llame al:
editTextFoo.dismiss()