Cerrar / ocultar el teclado de software de Android


Tengo un EditText y a Button en mi diseño.

Después de escribir en el campo de edición y hacer clic en el Button, quiero ocultar el teclado virtual. Asumo que esto es un simple fragmento de código, pero ¿dónde puedo encontrar un ejemplo de ello?

Author: Vidar Vestnes, 2009-07-10

30 answers

Para ayudar a aclarar esta locura, me gustaría comenzar pidiendo disculpas en nombre de todos los usuarios de Android para el tratamiento francamente ridículo de Google del teclado de software. La razón por la que hay tantas respuestas, cada una diferente, para la misma pregunta simple es porque esta API, como muchas otras en Android, está horriblemente diseñada. No se me ocurre una forma educada de decirlo.

Quiero ocultar el teclado. Espero proporcionar Android con la siguiente declaración: Keyboard.hide(). Final. Muchas gracias mucho. Pero Android tiene un problema. Debe usar InputMethodManager para ocultar el teclado. OK, bien, esta es la API de Android para el teclado. ¡PERO! Se requiere tener un Context para obtener acceso al IMM. Ahora tenemos un problema. Es posible que desee ocultar el teclado de una clase estática o de utilidad que no tiene uso o necesidad de ningún Context. o, y mucho peor, el IMM requiere que especifique de qué View (o incluso peor, de qué Window) desea ocultar el teclado.

Esto es lo que hace que esconderse el teclado tan desafiante. Estimado Google: Cuando estoy buscando la receta para un pastel, no hay RecipeProvider en la Tierra que se negaría a proporcionarme la receta a menos que primero responda QUIÉN será el pastel y dónde se comerá!!

Esta triste historia termina con la fea verdad: para ocultar el teclado Android, se le pedirá que proporcione 2 formas de identificación: a Context y a View o a Window.

He creado un método de utilidad estática que puede hacer el trabajo MUY sólido, siempre que lo llame desde un Activity.

public static void hideKeyboard(Activity activity) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    //Find the currently focused view, so we can grab the correct window token from it.
    View view = activity.getCurrentFocus();
    //If no view currently has focus, create a new one, just so we can grab a window token from it
    if (view == null) {
        view = new View(activity);
    }
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

Tenga en cuenta que este método de utilidad SOLO funciona cuando se llama desde un Activity! El método anterior llama a getCurrentFocus del destino Activity para obtener el token de ventana adecuado.

Pero, supongamos que desea ocultar el teclado de un EditText alojado en un DialogFragment? No puedes usar el método anterior para eso:

hideKeyboard(getActivity()); //won't work

Esto no funcionará porque pasará una referencia al host Fragment Activity, que no tendrá enfoque control mientras se muestra el Fragment! ¡Órale! Entonces, para ocultar el teclado de fragmentos, recurro al nivel inferior, más común y más feo:

public static void hideKeyboardFrom(Context context, View view) {
    InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

A continuación se muestra información adicional obtenida de más tiempo perdido persiguiendo esta solución:

Acerca de windowSoftInputMode

Hay otro punto de disputa que hay que tener en cuenta. De forma predeterminada, Android asignará automáticamente el enfoque inicial al primer control EditText o enfocable en tu Activity. Naturalmente sigue que el InputMethod (típicamente el teclado de software) responderá al evento focus mostrándose. El atributo windowSoftInputMode en AndroidManifest.xml, cuando se establece en stateAlwaysHidden, indica al teclado que ignore este foco inicial asignado automáticamente.

<activity
    android:name=".MyActivity"
    android:windowSoftInputMode="stateAlwaysHidden"/>

Casi increíblemente, parece no hacer nada para evitar que el teclado se abra cuando se toca el control (a menos que focusable="false" y/o focusableInTouchMode="false" se asignen al control). Aparentemente, la configuración windowSoftInputMode se aplica solo a automático enfocar eventos, no enfocar eventos activados desde eventos táctiles.

Por lo tanto, stateAlwaysHidden es MUY mal nombrado de hecho. Tal vez debería llamarse ignoreInitialFocus en su lugar.

Espero que esto ayude.


ACTUALIZACIÓN: Más formas de obtener un token de ventana

Si no hay una vista enfocada (por ejemplo, puede suceder si acaba de cambiar fragmentos), hay otras vistas que proporcionarán un token de ventana útil.

Estas son alternativas para el código anterior if (view == null) view = new View(activity); Estas no refiérase explícitamente a su actividad.

Dentro de una clase de fragmento:

view = getView().getRootView().getWindowToken();

Dado un fragmento fragment como parámetro:

view = fragment.getView().getRootView().getWindowToken();

A partir del cuerpo del contenido:

view = findViewById(android.R.id.content).getRootView().getWindowToken();

ACTUALIZACIÓN 2: Enfoque claro para evitar mostrar el teclado de nuevo si abre la aplicación desde el fondo

Añadir esta línea al final del método:

view.clearFocus();

 1169
Author: rmirabelle,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-01-12 14:44:33

Puede forzar a Android a ocultar el teclado virtual usando el InputMethodManager , llamando hideSoftInputFromWindow, pasar el token de la ventana que contiene la vista enfocada.

// Check if no view has focus:
View view = this.getCurrentFocus();
if (view != null) {  
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

Esto obligará al teclado a estar oculto en todas las situaciones. En algunos casos, querrá pasar InputMethodManager.HIDE_IMPLICIT_ONLY como segundo parámetro para asegurarse de que solo oculta el teclado cuando el usuario no lo forzó explícitamente a aparecer (manteniendo presionado menu).

Nota: Si quieres hacer esto en Kotlin, uso: context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

 4204
Author: Reto Meier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-20 12:38:21

También es útil para ocultar el teclado de software:

getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
);

Esto se puede usar para suprimir el teclado hasta que el usuario toque realmente la vista EditText.

 754
Author: Garnet Ulrich,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-24 16:07:40

Tengo una solución más para ocultar el teclado:

InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);

Aquí pase HIDE_IMPLICIT_ONLY en la posición de showFlag y 0 en la posición de hiddenFlag. Se cerrará con fuerza el teclado de software.

 303
Author: Saurabh Pareek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-27 15:26:34

La solución de Meier funciona para mí también. En mi caso, el nivel superior de mi aplicación es un TabHost y quiero ocultar la palabra clave al cambiar de pestaña: obtengo el token de ventana de la vista TabHost.

tabHost.setOnTabChangedListener(new OnTabChangeListener() {
    public void onTabChanged(String tabId) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(tabHost.getApplicationWindowToken(), 0);
    }
}
 132
Author: mckoss,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-24 15:54:56

Por favor, pruebe este código en onCreate()

EditText edtView=(EditText)findViewById(R.id.editTextConvertValue);
edtView.setInputType(0);
 120
Author: Jeyavel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-24 18:15:06

Actualización: No se por qué esta solución ya no funciona ( acabo de probar en Android 23). Por favor, utilice la solución de Saurabh Pareek en su lugar. Aquí está:

InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
//Hide:
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
//Show
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);

Antigua respuesta:

//Show soft-keyboard:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
//hide keyboard :
 getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
 113
Author: Nguyen Minh Binh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:54
protected void hideSoftKeyboard(EditText input) {
    input.setInputType(0);
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(input.getWindowToken(), 0);    
}
 67
Author: Sreedev R,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-30 10:42:26

Si todas las otras respuestas aquí no funcionan para usted como le gustaría, hay otra forma de controlar manualmente el teclado.

Cree una función con la que administrará algunas de las propiedades de EditText:

public void setEditTextFocus(boolean isFocused) {
    searchEditText.setCursorVisible(isFocused);
    searchEditText.setFocusable(isFocused);
    searchEditText.setFocusableInTouchMode(isFocused);

    if (isFocused) {
        searchEditText.requestFocus();
    }
}

Entonces, asegúrese de que onFocus de la EditText abre / cierra el teclado:

searchEditText.setOnFocusChangeListener(new OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        if (v == searchEditText) {
            if (hasFocus) {
                // Open keyboard
                ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(searchEditText, InputMethodManager.SHOW_FORCED);
            } else {
                // Close keyboard
                ((InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(searchEditText.getWindowToken(), 0);
            }
        }
    }
});

Ahora, cuando quiera abrir el teclado llame manualmente:

setEditTextFocus(true);

Y para cerrar la llamada:

setEditTextFocus(false);
 60
Author: Rotemmiz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-24 15:55:42

Saurabh Pareek tiene la mejor respuesta hasta ahora.

También podría usar las banderas correctas, sin embargo.

/* hide keyboard */
((InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE))
    .toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);

/* show keyboard */
((InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE))
    .toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);

Ejemplo de uso real

/* click button */
public void onClick(View view) {      
  /* hide keyboard */
  ((InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE))
      .toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);

  /* start loader to check parameters ... */
}

/* loader finished */
public void onLoadFinished(Loader<Object> loader, Object data) {
    /* parameters not valid ... */

    /* show keyboard */
    ((InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE))
        .toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);

    /* parameters valid ... */
}
 51
Author: Alex,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:55:19

De tan buscando, aquí encontré una respuesta que funciona para mí

// Show soft-keyboard:
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);

// Hide soft-keyboard:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
 48
Author: shontauro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-24 21:09:51

La respuesta corta

En tu OnClick oyente llama al onEditorAction del EditText con IME_ACTION_DONE

button.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        someEditText.onEditorAction(EditorInfo.IME_ACTION_DONE)
    }
});

El drill-down

Siento que este método es mejor, más simple y más alineado con el patrón de diseño de Android. En el simple ejemplo anterior (y generalmente en la mayoría de los casos comunes) tendrás un EditText que tiene/tuvo foco y también generalmente fue el que invocó el teclado en primer lugar (definitivamente es capaz de invocarlo en muchos escenarios comunes). De la misma manera, debe ser el que suelte el teclado, generalmente eso puede ser hecho por un ImeAction. Solo vea cómo se comporta un EditText con android:imeOptions="actionDone", desea lograr el mismo comportamiento por los mismos medios.


Marque esta respuesta relacionada

 42
Author: Alex.F,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:54

Esto debería funcionar:

public class KeyBoard {

    public static void show(Activity activity){
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY); // show
    }

    public static void hide(Activity activity){
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); // hide
    }

    public static void toggle(Activity activity){
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
        if (imm.isActive()){
            hide(activity); 
        } else {
            show(activity); 
        }
    }
}

KeyBoard.toggle(activity);
 40
Author: slinden77,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-15 14:51:17

Estoy usando un teclado personalizado para ingresar un número hexadecimal, por lo que no puedo hacer que aparezca el teclado IMM...

En v3. 2. 4_r1 setSoftInputShownOnFocus(boolean show) se agregó para controlar el tiempo o no para mostrar el teclado cuando un TextView recibe enfoque, pero sigue oculto, por lo que se debe usar reflexión:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
    try {
        Method method = TextView.class.getMethod("setSoftInputShownOnFocus", boolean.class);
        method.invoke(mEditText, false);
    } catch (Exception e) {
        // Fallback to the second method
    }
}

Para versiones anteriores, obtuve muy buenos resultados (pero lejos de ser perfectos) con un OnGlobalLayoutListener, agregado con la ayuda de un ViewTreeObserver desde mi vista raíz y luego comprobando si el teclado se muestra como esto:

@Override
public void onGlobalLayout() {
    Configuration config = getResources().getConfiguration();

    // Dont allow the default keyboard to show up
    if (config.keyboardHidden != Configuration.KEYBOARDHIDDEN_YES) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(mRootView.getWindowToken(), 0);
    }
}

Esta última solución puede mostrar el teclado durante una fracción de segundo y se mete con los controladores de selección.

Cuando en el teclado entra a pantalla completa, no se llama a onGlobalLayout. Para evitar esto, use TextView#setImeOptions (int) o en la declaración XML TextView:

android:imeOptions="actionNone|actionUnspecified|flagNoFullscreen|flagNoExtractUi"

Update: Acabo de encontrar lo que los diálogos usan para nunca mostrar el teclado y funciona en todas las versiones:

getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
        WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
 38
Author: sergio91pt,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-28 20:48:33
public void setKeyboardVisibility(boolean show) {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    if(show){
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    }else{
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),0);
    }
}
 29
Author: shobhan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-01 13:36:12

He pasado más de dos días trabajando a través de todas las soluciones publicadas en el hilo y las he encontrado faltantes de una manera u otra. Mi requisito exacto es tener un botón que muestre u oculte el teclado en pantalla con 100% de fiabilidad. Cuando el teclado está en su estado oculto no debería volver a aparecer, sin importar en qué campos de entrada haga clic el usuario. Cuando está en su estado visible, el teclado no debe desaparecer sin importar qué botones haga clic el usuario. Esto necesita trabaja en Android 2.2+ hasta los últimos dispositivos.

Puedes ver una implementación de trabajo de esto en mi aplicación clean RPN.

Después de probar muchas de las respuestas sugeridas en varios teléfonos diferentes (incluidos los dispositivos froyo y gingerbread) se hizo evidente que las aplicaciones de Android pueden confiar:

  1. ocultar Temporalmente el teclado. Volverá a aparecer cuando un usuario enfoca un nuevo campo de texto.
  2. Mostrar el teclado cuando se inicia una actividad y establecer una bandera en la actividad que indica que el teclado debe estar siempre visible. Este indicador solo se puede establecer cuando una actividad inicialización.
  3. Marcar una actividad para nunca mostrar o permitir el uso de la teclado. Este indicador solo se puede establecer cuando una actividad inicialización.

Para mí, ocultar temporalmente el teclado no es suficiente. En algunos dispositivos volverá a aparecer tan pronto como se enfoque un nuevo campo de texto. Como mi aplicación usa múltiples campos de texto en una página, enfocando un nuevo el campo de texto hará que el teclado oculto vuelva a aparecer.

Desafortunadamente, los ítems 2 y 3 de la lista solo funcionan con fiabilidad cuando se inicia una actividad. Una vez que la actividad se ha hecho visible, no puede ocultar o mostrar permanentemente el teclado. El truco es reiniciar realmente su actividad cuando el usuario presiona el botón de palanca del teclado. En mi aplicación cuando el usuario presiona el botón del teclado toggle, se ejecuta el siguiente código:

private void toggleKeyboard(){

    if(keypadPager.getVisibility() == View.VISIBLE){
        Intent i = new Intent(this, MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        Bundle state = new Bundle();
        onSaveInstanceState(state);
        state.putBoolean(SHOW_KEYBOARD, true);
        i.putExtras(state);

        startActivity(i);
    }
    else{
        Intent i = new Intent(this, MainActivity.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
        Bundle state = new Bundle();
        onSaveInstanceState(state);
        state.putBoolean(SHOW_KEYBOARD, false);
        i.putExtras(state);

        startActivity(i);
    }
}

Esto causa la actividad actual para tener su estado guardado en un Paquete, y luego se inicia la actividad, pasando por un booleano que indica si el teclado debe mostrarse u ocultarse.

Dentro del método onCreate se ejecuta el siguiente código:

if(bundle.getBoolean(SHOW_KEYBOARD)){
    ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(newEquationText,0);
    getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
else{
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
            WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
}

Si se debe mostrar el teclado de software, entonces se le dice al InputMethodManager que muestre el teclado y se le indica a la ventana que haga siempre visible la entrada de software. Si el teclado de software debe estar oculto, entonces el Administrador de ventanas.LayoutParams.FLAG_ALT_FOCUSABLE_IM está establecido.

Este enfoque funciona de manera fiable en todos los dispositivos que he probado - desde un teléfono HTC de 4 años de edad con Android 2.2 hasta un nexus 7 con 4.2.2. La única desventaja con este enfoque es que debe tener cuidado con el manejo del botón atrás. Como mi aplicación esencialmente solo tiene una pantalla (es una calculadora) puedo anular onBackPressed () y volver a la pantalla de inicio de los dispositivos.

 25
Author: Luke Sleeman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-06 07:10:29

Alternativamente a esta solución todo alrededor, si desea cerrar el teclado de software desde cualquier lugar sin tener una referencia al campo (EditText) que se usó para abrir el teclado, pero aún así desea hacerlo si el campo estaba enfocado, puede usar esto (desde una actividad):

if (getCurrentFocus() != null) {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
 24
Author: Saran,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:10:54

Gracias a this SO answer, derivé lo siguiente que, en mi caso, funciona muy bien cuando se desplaza a través de los fragmentos de un ViewPager...

private void hideKeyboard() {   
    // Check if no view has focus:
    View view = this.getCurrentFocus();
    if (view != null) {
        InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
}

private void showKeyboard() {   
    // Check if no view has focus:
    View view = this.getCurrentFocus();
    if (view != null) {
        InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
    }
}
 21
Author: ban-geoengineering,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 12:34:58

Las respuestas anteriores funcionan para diferentes escenarios, pero Si desea ocultar el teclado dentro de una vista y lucha por obtener el contexto correcto, intente esto:

setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        hideSoftKeyBoardOnTabClicked(v);
    }
}

private void hideSoftKeyBoardOnTabClicked(View v) {
    if (v != null && context != null) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(v.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
}

Y para obtener el contexto obtenerlo del constructor:)

public View/RelativeLayout/so and so (Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    this.context = context;
    init();
}
 18
Author: Ash,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-24 21:10:37

Si desea cerrar el teclado durante una unidad o prueba funcional, puede hacerlo haciendo clic en el" botón atrás " de su prueba:

// Close the soft keyboard from a Test
getInstrumentation().sendKeyDownUpSync(KeyEvent.KEYCODE_BACK);

Pongo "botón atrás" entre comillas, ya que lo anterior no activa el onBackPressed() para la Actividad en cuestión. Solo cierra el teclado.

Asegúrese de pausar un poco antes de continuar, ya que tarda un poco en cerrar el botón atrás, por lo que los clics posteriores a las vistas, etc., no se registrará hasta después de una breve pausa (1 segundo es lo suficientemente largo ime).

 17
Author: Peter Ajtai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-13 21:55:41

Así es como lo haces en Mono para Android (TAMBIÉN conocido como MonoDroid)

InputMethodManager imm = GetSystemService (Context.InputMethodService) as InputMethodManager;
if (imm != null)
    imm.HideSoftInputFromWindow (searchbox.WindowToken , 0);
 14
Author: BahaiResearch.com,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-05-15 01:36:10

Esto funcionó para mí por todo el extraño comportamiento del teclado

private boolean isKeyboardVisible() {
    Rect r = new Rect();
    //r will be populated with the coordinates of your view that area still visible.
    mRootView.getWindowVisibleDisplayFrame(r);

    int heightDiff = mRootView.getRootView().getHeight() - (r.bottom - r.top);
    return heightDiff > 100; // if more than 100 pixels, its probably a keyboard...
}

protected void showKeyboard() {
    if (isKeyboardVisible())
        return;
    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    if (getCurrentFocus() == null) {
        inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    } else {
        View view = getCurrentFocus();
        inputMethodManager.showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }
}

protected void hideKeyboard() {
    if (!isKeyboardVisible())
        return;
    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    View view = getCurrentFocus();
    if (view == null) {
        if (inputMethodManager.isAcceptingText())
            inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS, 0);
    } else {
        if (view instanceof EditText)
            ((EditText) view).setText(((EditText) view).getText().toString()); // reset edit text bug on some keyboards bug
        inputMethodManager.hideSoftInputFromInputMethod(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
}
 13
Author: Pinhassi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-24 21:11:16

Agregue a su actividad android:windowSoftInputMode="stateHidden" en el archivo de manifiesto. Ejemplo:

<activity
            android:name=".ui.activity.MainActivity"
            android:label="@string/mainactivity"
            android:windowSoftInputMode="stateHidden"/>
 13
Author: NickUnuchek,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-04 12:21:40

Usa esto

this.getWindow().setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
 11
Author: Atish Agrawal,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-08-09 13:42:00

Para mi caso, estaba usando la vista de búsqueda a en la barra de acción. Después de que un usuario realice una búsqueda, el teclado se abrirá nuevamente.

Usando el InputMethodManager no se cerró el teclado. Tuve que ClearFocus y establecer el enfocable de la vista de búsqueda en false:

mSearchView.clearFocus();
mSearchView.setFocusable(false);
 11
Author: tommy chheng,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-24 21:10:48

Casi he probado todas estas respuestas, tuve algunos problemas aleatorios, especialmente con el samsung galaxy s5.

Lo que acabo con es forzar el espectáculo y esconderse, y funciona perfectamente:

/**
 * Force show softKeyboard.
 */
public static void forceShow(@NonNull Context context) {
    InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
}

/**
 * Force hide softKeyboard.
 */
public static void forceHide(@NonNull Activity activity, @NonNull EditText editText) {
    if (activity.getCurrentFocus() == null || !(activity.getCurrentFocus() instanceof EditText)) {
        editText.requestFocus();
    }
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
 11
Author: ahmed_khan_89,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-15 12:40:06

En algunos casos este método puede funcionar excepto en todos los demás. Esto salva mi día:)

public static void hideSoftKeyboard(Activity activity) {
    if (activity != null) {
        InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (activity.getCurrentFocus() != null && inputManager != null) {
            inputManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
            inputManager.hideSoftInputFromInputMethod(activity.getCurrentFocus().getWindowToken(), 0);
        }
    }
}

public static void hideSoftKeyboard(View view) {
    if (view != null) {
        InputMethodManager inputManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputManager != null) {
            inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
}
 11
Author: iscariot,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-04 11:46:12

Método simple y fácil de usar, simplemente llame a hideKeyboardFrom(YourActivity.esto); para ocultar el teclado

/**
 * This method is used to hide keyboard
 * @param activity
 */
public static void hideKeyboardFrom(Activity activity) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
 11
Author: Naveed Ahmad,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-21 06:52:20

Simplemente use este código optimizado en su actividad:

if (this.getCurrentFocus() != null) {
    InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
 10
Author: Hamid FzM,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-24 21:11:54

Tengo el caso, donde mi EditText se puede ubicar también en un AlertDialog, por lo que el teclado debe cerrarse en dismiss. El siguiente código parece estar funcionando en cualquier lugar:

public static void hideKeyboard( Activity activity ) {
    InputMethodManager imm = (InputMethodManager)activity.getSystemService( Context.INPUT_METHOD_SERVICE );
    View f = activity.getCurrentFocus();
    if( null != f && null != f.getWindowToken() && EditText.class.isAssignableFrom( f.getClass() ) )
        imm.hideSoftInputFromWindow( f.getWindowToken(), 0 );
    else 
        activity.getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN );
}
 10
Author: injecteer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-24 21:12:20