Fermer / masquer le clavier Android Soft

J’ai un EditText et un Button dans ma mise en page.

Après avoir écrit dans le champ d’édition et cliqué sur le Button , je veux masquer le clavier virtuel. Je suppose que c’est un code simple, mais où puis-je en trouver un exemple?

Pour aider à clarifier cette folie, je voudrais commencer par m’excuser au nom de tous les utilisateurs d’Android pour le traitement ridicule de Google sur le clavier logiciel. La raison pour laquelle il y a tant de réponses, chacune différente, pour la même question simple est que cette API, comme beaucoup d’autres dans Android, est horriblement conçue. Je ne peux penser à aucune manière polie de le dire.

Je veux cacher le clavier. Je m’attends à fournir à Android l’instruction suivante: Keyboard.hide() . La fin. Merci beaucoup. Mais Android a un problème. Vous devez utiliser le InputMethodManager pour masquer le clavier. OK, c’est bien l’API d’Android sur le clavier. MAIS! Vous devez avoir un Context pour avoir access au module IMM. Maintenant, nous avons un problème. Je souhaiterais peut-être masquer le clavier à une classe statique ou utilitaire qui ne sert à rien ou n’a besoin d’aucun Context . Ou Et pire encore, le module IMM nécessite que vous spécifiiez quelle View (ou pire encore, quelle Window ) vous souhaitez masquer le clavier FROM.

C’est ce qui rend difficile la dissimulation du clavier. Cher Google: Quand je cherche la recette d’un gâteau, il n’y a pas de RecipeProvider sur Terre qui refuserait de me fournir la recette à moins que je ne réponde à l’OMS que le gâteau sera mangé ET où il sera mangé !!

Cette sortingste histoire se termine par la vilaine vérité: pour cacher le clavier Android, vous devrez fournir 2 formes d’identification: un Context et une View ou une Window .

J’ai créé une méthode d’utilitaire statique qui peut faire le travail TRÈS solidement, à condition que vous l’appeliez à partir d’une 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); } 

Sachez que cette méthode utilitaire ne fonctionne que lorsqu’elle est appelée depuis une Activity ! La méthode ci-dessus appelle getCurrentFocus de l’ Activity cible pour récupérer le jeton de fenêtre approprié.

Mais supposons que vous vouliez cacher le clavier d’un EditText hébergé dans un DialogFragment ? Vous ne pouvez pas utiliser la méthode ci-dessus pour cela:

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

Cela ne fonctionnera pas car vous transmettez une référence à l’ Activity hôte du Fragment , qui n’aura aucun contrôle ciblé lorsque le Fragment est affiché! Hou la la! Donc, pour cacher le clavier aux fragments, je recourt au niveau inférieur, plus commun et plus laid:

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

Vous trouverez ci-dessous des informations supplémentaires tirées de la perte de temps nécessaire à la poursuite de cette solution:

A propos de windowSoftInputMode

Il y a encore un autre sharepoint discorde à connaître. Par défaut, Android atsortingbue automatiquement le focus initial au premier contrôle EditText ou EditText de votre Activity . Il s’ensuit naturellement que la méthode InputMethod (généralement le clavier logiciel) répondra à l’événement focus en se montrant. L’atsortingbut windowSoftInputMode dans AndroidManifest.xml , lorsqu’il est défini sur stateAlwaysHidden , demande au clavier d’ignorer ce focus initial automatiquement atsortingbué.

  

De manière presque incroyable, il semble ne rien faire pour empêcher le clavier de s’ouvrir lorsque vous touchez le contrôle (sauf si focusable="false" et / ou focusableInTouchMode="false" sont affectés au contrôle). Apparemment, le paramètre windowSoftInputMode s’applique uniquement aux événements de focus automatiques, et non aux événements déclenchés par des événements tactiles.

Par conséquent, stateAlwaysHidden est TRÈS mal nommé. On devrait peut-être l’appeler ignoreInitialFocus .

J’espère que cela t’aides.


MISE À JOUR: Plus de façons d’obtenir un jeton de fenêtre

S’il n’y a pas de vue concentrée (par exemple, si vous venez de changer de fragment), d’autres vues vous fourniront un jeton de fenêtre utile.

Ce sont des alternatives pour le code ci-dessus if (view == null) view = new View(activity); Celles-ci ne font pas explicitement référence à votre activité.

Dans une classe de fragment:

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

Étant donné un fragment fragment en paramètre:

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

À partir de votre corps de contenu:

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

MISE À JOUR 2: Effacer la mise au point pour éviter de montrer à nouveau le clavier si vous ouvrez l’application à partir de l’arrière-plan

Ajoutez cette ligne à la fin de la méthode:

view.clearFocus();

Vous pouvez forcer Android à masquer le clavier virtuel à l’aide du InputMethodManager , en appelant hideSoftInputFromWindow , en transmettant le jeton de la fenêtre contenant votre vue focalisée.

 // 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); } 

Cela forcera le clavier à être caché dans toutes les situations. Dans certains cas, vous souhaiterez passer InputMethodManager.HIDE_IMPLICIT_ONLY en InputMethodManager.HIDE_IMPLICIT_ONLY que second paramètre pour vous assurer de ne masquer le clavier que lorsque l’utilisateur ne le force pas explicitement à apparaître (en maintenant le menu enfoncé).

Note: Si vous voulez faire cela dans Kotlin, utilisez: context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

Aussi utile pour cacher le clavier logiciel est:

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

Cela peut être utilisé pour supprimer le clavier logiciel jusqu’à ce que l’utilisateur touche la vue editText.

J’ai une autre solution pour cacher le clavier:

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

HIDE_IMPLICIT_ONLY à la position de showFlag et 0 à la position de hiddenFlag . Il fermera de force le clavier souple.

La solution de Meier fonctionne aussi pour moi. Dans mon cas, le niveau supérieur de mon application est un tabHost et je veux masquer le mot-clé lors du changement d’onglet – J’obtiens le jeton de la fenêtre ViewHost.

 tabHost.setOnTabChangedListener(new OnTabChangeListener() { public void onTabChanged(Ssortingng tabId) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(tabHost.getApplicationWindowToken(), 0); } } 

S’il vous plaît essayer ce code ci-dessous dans onCreate()

 EditText edtView=(EditText)findViewById(R.id.editTextConvertValue); edtView.setInputType(0); 

Mise à jour: Je ne sais pas pourquoi cette solution ne fonctionne plus (je viens de tester sur Android 23). Veuillez utiliser la solution de Saurabh Pareek à la place. C’est ici:

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

Vieille réponse:

 //Show soft-keyboard: getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE); //hide keyboard : getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); 
 protected void hideSoftKeyboard(EditText input) { input.setInputType(0); InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(input.getWindowToken(), 0); } 

Si toutes les autres réponses ne fonctionnent pas comme vous le souhaitez, il existe une autre façon de contrôler manuellement le clavier.

Créez une fonction qui gérera certaines des propriétés de EditText :

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

Ensuite, assurez-vous que onFocus de EditText vous ouvrez / fermez le clavier:

 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); } } } }); 

Maintenant, chaque fois que vous voulez ouvrir le clavier manuellement, appelez:

 setEditTextFocus(true); 

Et pour clore l’appel:

 setEditTextFocus(false); 

Saurabh Pareek a la meilleure réponse à ce jour.

Peut aussi bien utiliser les drapeaux corrects.

 /* 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); 

Exemple d’utilisation réelle

 /* 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 loader, Object data) { /* parameters not valid ... */ /* show keyboard */ ((InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE)) .toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY); /* parameters valid ... */ } 

de la recherche, j’ai trouvé une réponse qui fonctionne pour moi

 // 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); 

La réponse courte

Dans votre écouteur OnClick appelez onEditorAction du EditText avec IME_ACTION_DONE

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

Le forage

Je pense que cette méthode est meilleure, plus simple et mieux alignée sur le modèle de conception d’Android. Dans l’exemple simple ci-dessus (et généralement dans la plupart des cas courants), vous aurez un EditText qui a / avait le focus et qui EditText habituellement le clavier (il est certainement capable de l’invoquer dans de nombreux scénarios courants). De la même manière, il devrait être celui qui libère le clavier, généralement cela peut être fait par une ImeAction . Voyez comment un EditText avec android:imeOptions="actionDone" se comporte, vous voulez obtenir le même comportement par le même moyen.


Vérifiez cette réponse connexe

Cela devrait fonctionner:

 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); 

J’utilise un clavier personnalisé pour entrer un numéro Hex, donc je ne peux pas faire apparaître le clavier IMM …

En v3.2.4_r1, setSoftInputShownOnFocus(boolean show) été ajouté pour contrôler la météo ou ne pas afficher le clavier lorsqu’un object TextView obtient le focus, mais il est toujours caché pour que la reflection soit utilisée:

 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 } } 

Pour les versions plus anciennes, j’ai obtenu de très bons résultats (mais loin d’être parfaits) avec un OnGlobalLayoutListener , ajouté à l’aide d’un ViewTreeObserver depuis ma vue racine, puis en vérifiant si le clavier est affiché comme ceci:

 @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); } } 

Cette dernière solution peut afficher le clavier pendant une fraction de seconde et perturber les poignées de sélection.

Lorsque le clavier entre en plein écran, onGlobalLayout n’est pas appelé. Pour éviter cela, utilisez TextView # setImeOptions (int) ou dans la déclaration XML TextView:

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

Mise à jour: Vous venez de trouver les boîtes de dialog utilisées pour ne jamais afficher le clavier et fonctionne dans toutes les versions:

 getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM, WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM); 
 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); } } 

J’ai passé plus de deux jours à travailler sur toutes les solutions affichées dans le fil de discussion et les ai trouvées manquantes d’une manière ou d’une autre. Mon exigence exacte est d’avoir un bouton qui, avec une fiabilité à 100%, affichera ou masquera le clavier à l’écran. Lorsque le clavier est caché, son état ne doit pas réapparaître, quels que soient les champs de saisie sur lesquels l’utilisateur clique. Lorsqu’il est dans son état visible, le clavier ne doit pas disparaître, quels que soient les boutons sur lesquels l’utilisateur clique. Cela doit fonctionner sur Android 2.2+ jusqu’aux périphériques les plus récents.

Vous pouvez voir une implémentation fonctionnelle de ceci dans mon application RPN propre .

Après avoir testé un grand nombre des réponses suggérées sur un certain nombre de téléphones (y compris les appareils Froyo et Gingerbread), il est devenu évident que les applications Android peuvent être fiables:

  1. Masquer temporairement le clavier. Il réapparaîtra à nouveau lorsqu’un utilisateur concentre un nouveau champ de texte.
  2. Affichez le clavier lorsqu’une activité démarre et définissez un indicateur sur l’activité pour indiquer que le clavier doit toujours être visible. Cet indicateur ne peut être défini que lors de l’initialisation d’une activité.
  3. Marquez une activité pour ne jamais afficher ou autoriser l’utilisation du clavier. Cet indicateur ne peut être défini que lors de l’initialisation d’une activité.

Pour moi, masquer temporairement le clavier ne suffit pas. Sur certains appareils, il réapparaîtra dès qu’un nouveau champ de texte est concentré. Comme mon application utilise plusieurs champs de texte sur une seule page, la mise au point d’un nouveau champ de texte entraînera la réactivation du clavier caché.

Malheureusement, les points 2 et 3 de la liste ne sont fiables que lors du démarrage d’une activité. Une fois l’activité visible, vous ne pouvez plus masquer ou afficher le clavier de manière permanente. L’astuce consiste à redémarrer réellement votre activité lorsque l’utilisateur appuie sur le bouton de basculement du clavier. Dans mon application, lorsque l’utilisateur appuie sur le bouton du clavier à bascule, le code suivant s’exécute:

 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); } } 

Cela fait que l’activité en cours a son état enregistré dans un ensemble, puis l’activité est lancée, en passant par un booléen qui indique si le clavier doit être affiché ou masqué.

Dans la méthode onCreate, le code suivant est exécuté:

 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 le clavier logiciel doit être affiché, le InputMethodManager doit afficher le clavier et la fenêtre est chargée de rendre l’entrée logicielle toujours visible. Si le clavier logiciel doit être masqué, alors WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM est défini.

Cette approche fonctionne de manière fiable sur tous les appareils que j’ai testés – depuis un téléphone HTC de 4 ans fonctionnant sous Android 2.2 jusqu’à un Nexus 7 fonctionnant en 4.2.2. Le seul inconvénient de cette approche est que vous devez être prudent avec le bouton Retour. Comme mon application n’a qu’un seul écran (c’est une calculasortingce), je peux remplacer onBackPressed () et retourner à l’écran des appareils.

Alternatively to this all around solution , if you wanted to close the soft keyboard from anywhere without having a reference to the (EditText) field that was used to open the keyboard, but still wanted to do it if the field was focused, you could use this (from an Activity):

 if (getCurrentFocus() != null) { InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0); } 

Thanks to this SO answer , I derived the following which, in my case, works nicely when scrolling through the the fragments of a 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); } } 

Above answers work for different scenario’s but If you want to hide the keyboard inside a view and struggling to get the right context try this:

 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); } } 

and to get the context fetch it from constructor:)

 public View/RelativeLayout/so and so (Context context, AtsortingbuteSet attrs, int defStyle) { super(context, attrs, defStyle); this.context = context; init(); } 

If you want to close the soft keyboard during a unit or functional test, you can do so by clicking the “back button” from your test:

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

I put “back button” in quotes, since the above doesn’t sortinggger the onBackPressed() for the Activity in question. It just closes the keyboard.

Make sure to pause for a little while before moving on, since it takes a little while to close the back button, so subsequent clicks to Views, etc., won’t be registered until after a short pause (1 second is long enough ime).

Here’s how you do it in Mono for Android (AKA MonoDroid)

 InputMethodManager imm = GetSystemService (Context.InputMethodService) as InputMethodManager; if (imm != null) imm.HideSoftInputFromWindow (searchbox.WindowToken , 0); 

This worked for me for all the bizarre keyboard behavior

 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().toSsortingng()); // reset edit text bug on some keyboards bug inputMethodManager.hideSoftInputFromInputMethod(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } } 

Add to your activity android:windowSoftInputMode="stateHidden" in Manifest file. Exemple:

  

utilisez ceci

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

For my case, I was using the a SearchView in the actionbar. After a user performs a search, the keyboard would pop open again.

Using the InputMethodManager did not close the keyboard. I had to clearFocus and set the focusable of the search view to false:

 mSearchView.clearFocus(); mSearchView.setFocusable(false); 

I have almost sortinged all of these answers, I had some random issues especially with the samsung galaxy s5.

What I end up with is forcing the show and hide, and it works perfectly:

 /** * 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); } 

In some cases this methods can works except of all others. This saves my day 🙂

 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); } } } 

Simple and Easy to use method, just call hideKeyboardFrom(YourActivity.this); to hide keyboard

 /** * 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); } 

Just use this optimized code in your activity:

 if (this.getCurrentFocus() != null) { InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE); inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS); } 

I have the case, where my EditText can be located also in an AlertDialog , so the keyboard should be closed on dismiss. The following code seems to be working anywhere:

 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 ); }