@aminography 2020-07-04 12:45:57

Kotlin Version via Extension Function

Using kotlin extension functions, it'd be so simple to show and hide the soft keyboard.


import android.app.Activity
import android.view.View
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import androidx.fragment.app.Fragment

fun Activity.hideKeyboard(): Boolean {
    return (getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager)
        .hideSoftInputFromWindow((currentFocus ?: View(this)).windowToken, 0)

fun Fragment.hideKeyboard(): Boolean {
    return (context?.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager)
        .hideSoftInputFromWindow((activity?.currentFocus ?: View(context)).windowToken, 0)

fun EditText.hideKeyboard(): Boolean {
    return (context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager)
        .hideSoftInputFromWindow(windowToken, 0)

fun EditText.showKeyboard(): Boolean {
    return (context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager)
        .showSoftInput(this, 0)

• Usage

Now in your Activity or Fragment, hideKeyboard() is clearly accessible as well as calling it from an instance of EditText like:


@mckoss 2010-02-11 21:07:29

Meier's solution works for me too. In my case, the top level of my App is a tab host and I want to hide the keyword when switching tabs - I get the window token from the tab host View.

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

@Azurespot 2014-07-06 23:43:58

I got this to work with SearchView too. See below for my answer. Thanks mckoss!

@rmirabelle 2013-07-22 13:44:29

To help clarify this madness, I'd like to begin by apologizing on behalf of all Android users for Google's downright ridiculous treatment of the soft keyboard. The reason there are so many answers, each different, for the same simple question is because this API, like many others in Android, is horribly designed. I can think of no polite way to state it.

I want to hide the keyboard. I expect to provide Android with the following statement: Keyboard.hide(). The end. Thank you very much. But Android has a problem. You must use the InputMethodManager to hide the keyboard. OK, fine, this is Android's API to the keyboard. BUT! You are required to have a Context in order to get access to the IMM. Now we have a problem. I may want to hide the keyboard from a static or utility class that has no use or need for any Context. or And FAR worse, the IMM requires that you specify what View (or even worse, what Window) you want to hide the keyboard FROM.

This is what makes hiding the keyboard so challenging. Dear Google: When I'm looking up the recipe for a cake, there is no RecipeProvider on Earth that would refuse to provide me with the recipe unless I first answer WHO the cake will be eaten by AND where it will be eaten!!

This sad story ends with the ugly truth: to hide the Android keyboard, you will be required to provide 2 forms of identification: a Context and either a View or a Window.

I have created a static utility method which can do the job VERY solidly, provided you call it from an 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);

Be aware that this utility method ONLY works when called from an Activity! The above method calls getCurrentFocus of the target Activity to fetch the proper window token.

But suppose you want to hide the keyboard from an EditText hosted in a DialogFragment? You can't use the method above for that:

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

This won't work because you'll be passing a reference to the Fragment's host Activity, which will have no focused control while the Fragment is shown! Wow! So, for hiding the keyboard from fragments, I resort to the lower-level, more common, and uglier:

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

Below is some additional information gleaned from more time wasted chasing this solution:

About windowSoftInputMode

There's yet another point of contention to be aware of. By default, Android will automatically assign initial focus to the first EditText or focusable control in your Activity. It naturally follows that the InputMethod (typically the soft keyboard) will respond to the focus event by showing itself. The windowSoftInputMode attribute in AndroidManifest.xml, when set to stateAlwaysHidden, instructs the keyboard to ignore this automatically-assigned initial focus.


Almost unbelievably, it appears to do nothing to prevent the keyboard from opening when you touch the control (unless focusable="false" and/or focusableInTouchMode="false" are assigned to the control). Apparently, the windowSoftInputMode setting applies only to automatic focus events, not to focus events triggered by touch events.

Therefore, stateAlwaysHidden is VERY poorly named indeed. It should perhaps be called ignoreInitialFocus instead.

Hope this helps.

UPDATE: More ways to get a window token

If there is no focused view (e.g. can happen if you just changed fragments), there are other views that will supply a useful window token.

These are alternatives for the above code if (view == null) view = new View(activity); These don't refer explicitly to your activity.

Inside a fragment class:

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

Given a fragment fragment as a parameter:

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

Starting from your content body:

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

UPDATE 2: Clear focus to avoid showing keyboard again if you open the app from the background

Add this line to the end of the method:


@Oyvind 2015-01-04 16:40:00

Very nice writeup. One thing however, if you start another activity on top of it, that triggers keyboard, the keyboard will still be present when you return. Fixed that by removing the keyboard using your method when quiting the top activity.

@McX 2015-06-11 16:09:10

@rmirabelle In a Fragment it seems that you can use getActivity().getWindow().getDecorView()

@PGMacDesign 2015-10-01 18:29:14

You can actually use your static method within a fragment just fine, you just need to cast the context into an activity. Code would look like this: hide_keyboard((MainActivity)getActivity()); Just replace the MainActivity with the name of the parent activity and it will work fine.

@Warpzit 2016-06-07 07:46:31

This post is great but you lack two very important part. The subtle changes done per version and done per manufacture. For example on a Samsung galaxy s6 we need to use .clearFocus() before hiding the keyboard... if not the keyboard will still pop up on second click of edittext :S

@Merlevede 2016-06-12 17:32:50

I totally agree with you!! This line view = new View(activity); is magic and insulting at the same time!! It's ridiculous that you have to create a useless view only to hide the keyboard, and it´s the only way it worked for me.

@HendraWD 2016-10-18 09:47:38

google should just really provide that Keyboard.hide(); utility

@ToolmakerSteve 2016-12-05 20:38:57

@mirabelle - given a fragment view, use view.getRootView() to get the view that has window token. So given a fragment: fragment.getView().getRootView().getWindowToken().

@Oliver Dixon 2017-04-26 12:38:56

[someView].getContext() << Can be case to activity. It's the same object always. (Except inside services...)

@oxied 2017-07-19 09:31:06

I recommend to add view.clearFocus();. In that way keyboard will not be shown if you put app to background and open it again (cause view is not focused now)

@Elyakim Levi 2017-10-12 12:06:05

This is the one that worked for me: view = getView().getRootView().getWindowToken();

@Matthias 2018-03-22 20:38:42

Even though the post reads really nice and I do understand the frustration, I disagree with just having 'Keyboard.hide()'. Let's say you have two apps running. Within the first one you are within an TextInput and the keyboard is active. Now you switch the other app to copy some text that you wanna paste into the other one - for instance your bank account number. Then you for sure don't want the keyboard to hide in the first app, but maybe in the second. Sounds complicated. But you want a fixed STATE for every app. So you need a view to tell the smartphone which keyboard for which app to close.

@Ready Android 2018-05-04 06:10:28

Yup, need to play with InputMethodManager with the INPUT_METHOD_SERVICE to handle soft keyboard like readyandroid.wordpress.com/show-hide-android-soft-keyboard

@user924 2018-08-28 07:31:25

it's not a problem to get Context from Util class, create create that extends Application set name for App in manifest, save Application instance as instance and create static method to get context from static Application instance, I don't see any problem

@Richard Stokes 2019-01-12 13:53:46

I think that providing the context isn't an issue as the soft keyboard is a UI element and as such should only be manipulated from your view which you'll always have easy access to the context. If there is a static method like Keyboard.hide then this might lead to bad practices, in particular, leading away from the single responsibility model.

@rmirabelle 2019-01-12 17:31:12

@RichardStokes Understood. But IMO, having to constantly manually 'protect' the UI thread (Context being the prime example) is one of Android's great shortcomings. And I prefer to handle things like SRP (a developer concern) without the SDK's verbose opinions littering my code. ;-)

@Eldhopj 2019-06-21 10:17:02

if white screen appears while hiding keyboard. add this code getWindow().getDecorView().setBackgroundColor( android.R.color.transparent); at OnCreate();

@Justin 2019-11-25 23:34:32

TL;DR in your activity in your android manifest, put: android:windowSoftInputMode="stateAlwaysHidden"

@Mark 2020-04-30 11:15:12

Surely View(activity).getWindowToken() is always null because if you look at the implementation (at least in View.java) then it will be null if mAttachInfo is null - and, in turn, this can only be non-null if dispatchAttachedToWindow() has been called - which it hasn't

@YoussefDir 2020-05-04 06:17:49

view = new View(activity); didn't work for me, instead I referenced an already existing view like this view = findViewById(R.id.editText_id); then it worked.

@AlexVPerl 2020-05-07 02:44:18

Thank you for this write up, very helpful. I think 1 improvement could be made to achieve a parameterless hideKeyboard(). WeakReference to currentActivity and currentFocusedView could be stored in the Application class, and retrieved from there. Since its a WeakReference, no memory leaks will occur.

@Leonid Ivankin 2020-02-17 07:21:59

When moving from fragment to fragment

fun hideKeyboard(activity: Activity?): Boolean {
    val inputManager = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
    if (inputManager != null) {
        val currentFocus = activity?.currentFocus
        if (currentFocus != null) {
            val windowToken = currentFocus.windowToken
            if (windowToken != null) {
                return inputManager.hideSoftInputFromWindow(windowToken, 0)
    return false

fun showKeyboard(editText: EditText) {
    val imm = editText.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(editText.windowToken, 0)
    imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0)

@Davinder Goel 2020-01-28 09:24:20

you can hide keyboard in Kotlin as well using this code snippet.

 fun hideKeyboard(activity: Activity?) {
    val inputManager: InputMethodManager? = 
    activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? 
    // check if no view has focus:
    val v = activity?.currentFocus ?: return
    inputManager?.hideSoftInputFromWindow(v.windowToken, 0)

@Junaid Bashir 2020-01-03 06:39:25

Just call the below method it will hide your keyboard if its showing.

public void hideKeyboard() {
    try {
        InputMethodManager inputmanager = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputmanager != null) {
            inputmanager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
    } catch (Exception var2) {


@Kalpesh Rupani 2020-01-15 10:30:39

By Adding the Generic method to your Utility or Helper class. By just calling itself you can hide and show keyboard

fun AppCompatActivity.hideKeyboard() {
            val view = this.currentFocus
            if (view != null) {
                val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.hideSoftInputFromWindow(view.windowToken, 0)


 fun AppCompatActivity.showKeyboard() {
            val view = this.currentFocus
            if (view != null) {
                val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
                imm.hideSoftInputFromWindow(view.windowToken, 0)
            }                     window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)


@Jake Jones 2019-12-28 13:45:08

just add this property in your EditTect view to hide keyboard.


@Scott Biggs 2020-01-20 05:55:13

You're just throwing darts, and this one not only missed the board, but almost hit the bartender.

@Sanket Naik 2019-12-27 09:02:06

For kotlin lovers. I have created two extension functions. For hideKeyboard fun, you can pass edittext's instance as a view.

fun Context.hideKeyboard(view: View) {
    (getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.apply {
        hideSoftInputFromWindow(view.windowToken, 0)

fun Context.showKeyboard() {
    (getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager)?.apply {
        toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY)

@Scott Biggs 2020-01-20 06:02:01

Seems to work, although it's kotlin complicated. thanks

@BENN1TH 2020-03-29 08:34:10

Nice, others answers didn't work, this did using MainActivity with EditText control

@inspire_coding 2020-04-03 13:07:32

The best answer I could use it with DataBinding either, thanks.

@Marium Jawed 2019-12-23 08:48:34

Easy way for you is to set the below attribute in your EditText View.


@norbDEV 2019-11-09 12:53:26

Works in a fragment with Android 10 (API 29)

val activityView = activity?.window?.decorView?.rootView
activityView?.let {
    val imm = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
    imm?.hideSoftInputFromWindow(it.windowToken, 0)

@Bhavik Nathani 2019-07-13 08:34:25

Just Add following line in AndroidManifest in specific activity.


@Salman Nazir 2019-10-21 13:57:34

In Kotli, I use Kotlin extensions for showing and hiding the Keyboard.

fun View.showKeyboard() {
  val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
  inputMethodManager.showSoftInput(this, InputMethodManager.SHOW_IMPLICIT)

fun View.hideKeyboard() {
  val inputMethodManager = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
  inputMethodManager.hideSoftInputFromWindow(windowToken, 0)

@Rahul Patil 2019-10-02 05:57:27

Try This Force fully android soft input keyborad

create Method in Helper class.

InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm != null)
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);

@Reto Meier 2009-07-10 11:52:00

You can force Android to hide the virtual keyboard using the InputMethodManager, calling hideSoftInputFromWindow, passing in the token of the window containing your focused view.

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

This will force the keyboard to be hidden in all situations. In some cases you will want to pass in InputMethodManager.HIDE_IMPLICIT_ONLY as the second parameter to ensure you only hide the keyboard when the user didn't explicitly force it to appear (by holding down menu).

Note: If you want to do this in Kotlin, use: context?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager

Kotlin Syntax

// Check if no view has focus:
 val view = this.currentFocus
 view?.let { v ->
  val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager 
  imm?.hideSoftInputFromWindow(v.windowToken, 0)

@RoflcoptrException 2010-06-23 22:50:24

Thanks this seems to work great if using 0 as the second parameter. But if I use InputMethodManager.HIDE_IMPLICIT_ONLY the keyboard is never hidden (although i'm not holding down menu). Any hints?

@Cheezmeister 2011-02-16 19:48:24

Cool. Just to clarify, this only dismisses it if present, but won't prevent it from popping up, right?

@ataulm 2011-04-16 17:52:27

@Roflcoptr - hideImplicitOnly is only when the keyboard automatically opens when an editText gets focus. In your situation, you may be pressing on the editText, indicating that you want to type in it, which is an explicit action.

@Androider 2011-05-23 13:36:07

Of course you will need to set this back. Please verify how to undo this change.

@Tirtha 2012-01-11 10:25:00

this causes the app to force close on android 1.5

@Bill the Lizard 2012-05-07 15:33:23

@RetoMeier Can you update this with what versions it works for, and if you can confirm which ones it doesn't?

@Dandre Allison 2012-07-04 15:50:31

I think I had to add an if imm is not null, for weird cases where it gets hidden for other reasons before that code runs.

@Timmmm 2012-07-30 13:55:44

Works for me on Android 4.1, but only if you use 0 and not HIDE_IMPLICIT_ONLY. Also it doesn't prevent the keyboard from popping up again. I use it with an EditText + send button, and when you run it, the EditText retains focus and the keyboard is hidden. Then when you tap the EditText the keyboard is shown again. Perfect!

@IgorGanapolsky 2012-08-10 18:49:29

This approach assumes that the specific EditText is not null. But suppose your user presses the Home button on the device, which invokes the onStop() method. Then any reference to an EditText can throw a NullPointerException.

@erdomester 2012-12-08 22:16:46

didn't work for me (Samsung Galaxy Ace 2.3.3, HTC Desire HD 2.3.5)

@Noumenon 2013-07-09 06:47:50

S3 here. This works when the keyboard is left open after its job is done, like when you close a dialog. When the focus is still in an EditText, use Garnet's solution.

@Jacky 2013-07-31 23:23:11

what's the exact meaning of "explicitly force it to appear (by holding down menu)."?

@user2224350 2013-10-01 19:51:31

It may be helpfully to call editText.clearFocus() before hiding the softInput

@sprocket12 2013-11-30 12:57:56

Calling editText.clearFocus() then InputMethodManager.HIDE_IMPLICIT_ONLY even works on 4.1

@jmuet 2014-02-03 09:46:57

what also can help, is to wrap this code into runnable and postDelayed to getCurrentFocus() View

@Sivakumar Purushothaman 2014-03-25 12:05:26

I have more than one edit text box in single xml layout. so at that time what can i do?

@Harpreet 2014-04-16 06:33:47

Guys, need to implement above code in both cases i.e. onFocus & onClick

@Mars 2014-05-14 10:40:15

tip: instead of getting your textview, which can be a problem if you don't know which one is focused, you can get the windows token using this: getWindow().getDecorView().getRootView().getWindowToken();

@Steve Waring 2014-07-29 06:42:25

With clear focus and test for nulls this works on my Galaxy S3. This is very useful as there is a bug in S3's soft keyboard. If you plug in USB keyboard with an EditText field using an ActionId of EditorInfo.IME_ACTION_DONE the soft keyboard is not hidden if the user hits enter on the hard keyboard. The user can use the back key to hide the soft keyboard, but adding this code to onEditorAction with an actionId != EditorInfo.IME_ACTION_DONE test makes the UI act as expected.

@McLovin 2014-08-01 15:34:17

@jmuet This is what also resolved the issue for me. By adding a small delay between resuming my fragment and hiding the keyboard, it now magically disappears: mHandler.postDelayed(new Runnable() { @Override public void run() { KeyboardUtils.hideKeyboard(getActivity()); } }, 200);

@Taeho Kim 2014-10-27 13:22:05

If the IME was not hidden by above method, you can try same method with switching myEditText.getWindowToken() into myEditText.getApplicationWindowToken().

@fffred 2015-01-02 20:33:35

Does not work on 2.3 and 5.0 when a long-press is done instead of double-click.

@Oleksiy 2015-04-16 16:57:35

You should use InputMethodManager.RESULT_UNCHANGED_SHOWN flag instead of the value 0

@Wes Winn 2015-07-08 02:21:17

Something worth noting is that if you're using this in a click listener's "public void onClick(View view)" method, just use THAT view. Android doesn't seem too concerned if that view is, say, a Login button, or whatever it happens to be. It still works.

@Ionoclast Brigham 2015-08-13 00:12:17

What worked for me on 4.4/htc was executing View focused = getCurrentFocus() to get what is definitely the currently focused view, calling focused.clearFocus(), and then inputMethodManager.hideSoftInputFromWindow(focused.getWindow‌​Token(), 0) (with clear flags).

@Marek 2015-10-10 17:03:10

It worked perfectly for me, until I added a DialogFragment, after dismiss of this DialogFragment your method does not work anymore...

@TomeeNS 2015-12-08 13:40:34

Android 4.*. There are situations when the keyboard is visible but no View is focused :[ ---> BUT here is what acutally worked for me: View focused = activ.getCurrentFocus(); if (focused != null){ focused.clearFocus(); InputMethodManager imm = (InputMethodManager)activ.getSystemService(Context.INPUT_MET‌​HOD_SERVICE); imm.hideSoftInputFromWindow(focused.getWindowToken(), 0); }

@Bron Davies 2015-12-23 20:08:20

use Handler h = new Handler(); h.postDelayed(runnable, 0); where the runnable executes this code - works on all versions of Android.

@Zin Win Htet 2016-03-17 04:34:24

In my case, when I replace another fragment to container, the soft keyboard is still showing. So I don't need to have any current focus.

@Warpzit 2016-06-07 07:28:43

On Samsung S6 edge it takes care of the first click, if you click again the keyboard pops up if you don't use .clearFocus(); as suggested earlier in the comments.

@foluis 2017-10-26 17:10:19

XAMARIN InputMethodManager inputManager = (InputMethodManager) this.GetSystemService(Context.InputMethodService); inputManager.HideSoftInputFromWindow(this.CurrentFocus.Windo‌​wToken, HideSoftInputFlags.NotAlways);

@Ready Android 2018-05-04 06:10:07

Nice, need to play with InputMethodManager with the INPUT_METHOD_SERVICE to handle soft keyboard like readyandroid.wordpress.com/show-hide-android-soft-keyboard

@KarlTheGreat 2019-07-13 19:30:57

An easy workaround ist to just editText.setEnabled(false);editText.setEnabled(true); in your Button onClick() method.

@Nikhil Katekhaye 2019-06-19 07:17:41

This was work for me. It is in Kotlin for hiding the keyboard.

private fun hideKeyboard() {
        val inputManager = activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        val focusedView = activity?.currentFocus
        if (focusedView != null) {

@Udara Abeythilake 2019-06-18 05:16:04

First, you should add from the XML file add android:imeOptions field and change its value to actionUnspecified|actionGo as below


Then In the java class add a setOnEditorActionListener and add InputMethodManager as below

enterOrderNumber.setOnEditorActionListener(new TextView.OnEditorActionListener() {

    public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
        if (actionId == EditorInfo.IME_ACTION_GO) {
            InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
            return true;
        return false;

@Selman Tosun 2019-05-27 10:52:38

This code snippet can helped:

    final InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
    if (inputMethodManager != null && inputMethodManager.isActive()) {
        if (getCurrentFocus() != null) {
            inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

It can be called in different methods according to need (ex. onPause, onResume, onRestart ...)

@Priyankagb 2019-02-26 06:12:36

just make common method for whole application in BaseActivity and BaseFragment

in onCreate() initialize inputMethodManager

inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

make this methods to hide & show keyboard

public void hideKeyBoard(View view) {
     if (view != null) {
         inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);

public void showKeyboard(View view, boolean isForceToShow) {
      if (isForceToShow)
         inputMethodManager.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
      else if (view != null)
           inputMethodManager.showSoftInput(view, 0);

@Arihant Jain 2019-02-20 08:33:44

Below code will help you to make generic function that can be call from anywhere.

import android.app.Activity
import android.content.Context
import android.support.design.widget.Snackbar
import android.view.View
import android.view.inputmethod.InputMethodManager

public class KeyboardHider {
    companion object {

        fun hideKeyboard(view: View, context: Context) {
            val inputMethodManager = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
            inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)



Call Above method from anywhere using one single line of code.

CustomSnackbar.hideKeyboard(view, [email protected])

view could be anything for example root layout of an activity.

@portfoliobuilder 2019-07-29 21:28:11

Is there any difference between Context.INPUT_METHOD_SERVICE and Activity.INPUT_METHOD_SERVICE? Both seem to work

@portfoliobuilder 2019-07-29 21:39:49

Also, you code sample will throw IllegalStateException

@Arihant Jain 2019-07-30 11:59:37

@portfoliobuilder where you think that it will throw the Exception?

@portfoliobuilder 2019-07-30 16:31:15

Lets say the user does standard implementation of hiding keyboard when app goes into background (onPause) and displaying it while in the foreground (onResume). Now lets also presume two screens. An illegalStateException can occur if keyboard is already hidden and transition occurs from Activity A to Activity B (or Fragment A to Fragment B, or Activity A to Fragment B, ect). You have no checks for if keyboard is visible already.

@Ambilpura Sunil Kumar 2019-02-16 11:22:15

there are two ways to do so...

method 1:in manifest file

define the line **android:windowSoftInputMode="adjustPan|stateAlwaysHidden"** of code in your manifest.xml file as below...

            android:windowSoftInputMode="adjustPan|stateAlwaysHidden" />

Method 2 : in Activity or Java class

 if(getCurrentFocus()!=null) {
            InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE)`enter code here`;
            inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

it will [email protected]

@hardiBSalih 2019-02-06 21:08:41

Hi This is simple if you are working with Kotlin i belive you can easily convert the code to Java too first in your activity use this function when your activity is load for example in the onCreate() call it.

fun hideKeybord (){
val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
if (inputManager.isAcceptingText){
    inputManager.hideSoftInputFromWindow(currentFocus.windowToken, 0)


as i mentiond call this Function in your onCreate() methode then add this android:windowSoftInputMode="stateAlwaysHidden" line to your activity in manafest.xml file Like this...


@Krasavello13 2018-11-28 16:43:31

If you use Kotlin for developing your application, it's really easy to do.

Add this extensions functions:

For Activity:

fun Activity.hideKeyboard() {
    val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    val view = currentFocus
    if (view != null) {
        inputManager.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)

For Fragment:

fun Fragment.hideKeyboard() {
    activity?.let {
        val inputManager = it.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        val view = it.currentFocus
        if (view != null) {
            inputManager.hideSoftInputFromWindow(view.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)

Now you can simple call in your Fragment or Activity:


@Sreedev R 2012-05-04 04:02:00

protected void hideSoftKeyboard(EditText input) {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(input.getWindowToken(), 0);    

@ymerdrengene 2014-04-10 13:52:53

This worked for me! But why did you put input.setInputType(0) ? I couldn't interact with the EditTextView when I had that line of code (It worked when I removed it).

@CoolMind 2018-09-19 14:28:11

Probably input.getContext().getSystemService(Context.INPUT_METHOD_SER‌​VICE).

@CoolMind 2018-11-28 10:56:21

I removed input.setInputType(0); from this code. It changed a keyboard behaviour and inputType for the EditText.

@shrewdu 2018-11-28 08:05:54

For the kotlin users out there here is a kotlin extension method that has worked for my use cases:

fun View.hideKeyboard() {
    val imm = this.context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(windowToken, 0)

put it in a file called ViewExtensions (or what have you) and call it on your views just like a normal method.

@user1765048 2012-11-20 14:05:39

sometimes all you want is the enter button to fold the keyboard give the EditText box you have the attribute


this will change the Enter button to a Done button that will close the keyboard.

@tmr 2014-10-25 06:37:03

in my case, in addition to android:imeOptions="actionDone" also needed to include android:singleLine="true"

@Rajneesh Shukla 2018-10-31 05:55:52

Call this method to hide the soft keyboard

public void hideKeyBoard() {
    View view1 = this.getCurrentFocus();
    if(view!= null){
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view1.getWindowToken(), 0);

@Janusz Hain 2018-03-07 09:01:13

I have written small extension for Kotlin if anyone interested, didn't test it much tho:

fun Fragment.hideKeyboard(context: Context = App.instance) {
    val windowToken = view?.rootView?.windowToken
    windowToken?.let {
        val imm = context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(windowToken, 0)

App.instance is static "this" Application object stored in Application

Update: In some cases windowToken is null. I have added additional way of closing keyboard using reflection to detect if keyboard is closed

 * If no window token is found, keyboard is checked using reflection to know if keyboard visibility toggle is needed
 * @param useReflection - whether to use reflection in case of no window token or not
fun Fragment.hideKeyboard(context: Context = MainApp.instance, useReflection: Boolean = true) {
    val windowToken = view?.rootView?.windowToken
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    windowToken?.let {
        imm.hideSoftInputFromWindow(windowToken, 0)
    } ?: run {
        if (useReflection) {
            try {
                if (getKeyboardHeight(imm) > 0) {
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS)
            } catch (exception: Exception) {

fun getKeyboardHeight(imm: InputMethodManager): Int = InputMethodManager::class.java.getMethod("getInputMethodWindowVisibleHeight").invoke(imm) as Int

@Phil 2018-10-25 07:49:01

Wiki answer in Kotlin :

1 - Create a top-level function inside a file (for example a file that contains all your top-level functions) :

fun Activity.hideKeyboard(){
    val imm = this.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    var view = currentFocus
    if (view == null) { view = View(this) }
    imm.hideSoftInputFromWindow(view.windowToken, 0)

2 - Then call it in any activity you needed it :


Related Questions

Sponsored Content

Sponsored Content