By Vidar Vestnes


2009-07-10 11:27:17 8 Comments

I have an EditText and a Button in my layout.

After writing in the edit field and clicking on the Button, I want to hide the virtual keyboard. I assume that this is a simple piece of code, but where can I find an example of it?

30 comments

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

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

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

Just Add following line in AndroidManifest in specific activity.

<activity
        android:name=".MainActivity"
        android:screenOrientation="portrait">
        android:windowSoftInputMode="adjustPan"/>

@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) {
            inputManager.hideSoftInputFromWindow(focusedView.windowToken,
                    InputMethodManager.HIDE_NOT_ALWAYS)
        }
    }

@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

 <android.support.design.widget.TextInputEditText
                    android:id="@+id/edit_text_id"
                    android:layout_width="fill_parent"
                    android:layout_height="@dimen/edit_text_height"
                    android:imeOptions="actionUnspecified|actionGo"
                    />

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

enterOrderNumber.setOnEditorActionListener(new TextView.OnEditorActionListener() {

    @Override
    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 ...)

@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?.let { it.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)

@Oleg Karakoz 2013-02-04 16:26:54

It does not work if u do not know exactly field owns focus.

@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).

@Lisa Anne 2015-09-10 10:42:09

Need to clear focus on the edittext!

@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

@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...

<activity
            android:name="packagename.youactivityname"
            android:screenOrientation="portrait"
            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...

<activity
    android:name=".Activity.MainActivity"
    android:label="@string/app_name"
    android:theme="@style/AppTheme.NoActionBar"
    android:windowSoftInputMode="stateAlwaysHidden">

@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:

 hideKeyboard()

@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.

@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 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.

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

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:

view.clearFocus();

@Kyle Ivey 2014-01-09 07:26:21

I don't think you should be modifying the softInputMode. This will override AndroidManifest settings.

@rmirabelle 2014-01-09 14:47:06

agreed that it's better in the manifest - this is just an attempt to brute force things

@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.

@G_V 2015-01-07 10:28:56

I was using the hide_keyboard method from a static utility class and it works great functionally but it lagged so hard! I can't fathom why android needs all this junk to hide the keyboard. I only need it on one activity so I guess I'll just make a bunch of stuff static inside that specific activity to avoid to creation overhead. I'm using it inside a ViewPager which makes performance issues that much more visible. Top quality post!

@Alexander Farber 2015-04-20 12:07:30

What is the view argument in hide_keyboard_from() method? Is it typically an EditText?

@rmirabelle 2015-04-20 18:30:54

@AlexanderFarber yes, typically an EditText, but I believe any visible View will work (e.g. TextView), since the View is only used to derive a window token (the thing to hide the keyboard from). Also, I believe the View should come from the host Activity rather than the Fragment

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

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

@Silmarilos 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.

@wm1sr 2016-09-12 17:34:07

I'm used to the Windows Phone's API, where everything seemed so simple compared to Android's. Most of the things you do in Android depends on a Context object. That's a hassle when creating utility methods. But I ended up getting used to it... It was hard in the beginning but now I just accept it, though it could be so much simpler.

@Neon Warge 2016-10-12 14:21:55

We have the same exact answer. Great one! I definitely agree about Android SDK being the worst out there. I've tried other SDK like Cocos2dx but sad to say Android is worst of them all. I guess this is just the reality when dealing with SDKs.

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

@batsheva 2017-09-05 12:02:26

thx!! helped me, and this is not the first thing i found so curved in android, so much bugs, and things that works for one and dosn't work for other... each control with his different behavior, things are not in common, this make it hard to work and develope...

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

@Khawar Raza 2019-08-01 11:20:59

I have more than 80 controls including text fields, labels and dropdowns scattered in different fragments and these fragments are placed in viewpager. Now when I click on edittext, type some text and press either done button or back navigation key, the app freezes for 2 to 4 seconds while keyboard hide animation is in progress. Any workaround for this?

@rmirabelle 2019-08-15 15:17:18

@KhawarRaza I suggest you submit this as a new question

@Khawar Raza 2019-08-15 15:33:41

@rmirabelle already did. stackoverflow.com/questions/57507527/…

@buckleyJohnson 2019-09-08 04:04:51

you whine about Android and you leave out the most obvious info: how to call your function

@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

 android:imeOptions="actionDone" 

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) {
                Timber.e(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 :

this.hideKeyboard()

@Coldfin Lab 2018-10-16 06:47:55

public void hideKeyboard() 
{
    if(getCurrentFocus()!=null) 
    {
        InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
    }
}


public void showKeyboard(View mView) {
    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
    mView.requestFocus();
    inputMethodManager.showSoftInput(mView, 0);
}

@Khemraj 2018-10-01 09:54:22

Here are both hide & show methods.

Kotlin

fun hideKeyboard(activity: Activity) {
    val v = activity.currentFocus
    val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(v != null)
    imm.hideSoftInputFromWindow(v!!.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
}

private fun showKeyboard(activity: Activity) {
    val v = activity.currentFocus
    val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    assert(v != null)
    imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT)
}

Java

public static void hideKeyboard(Activity activity) {
    View v = activity.getCurrentFocus();
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    assert imm != null && v != null;
    imm.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}

private static void showKeyboard(Activity activity) {
    View v = activity.getCurrentFocus();
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    assert imm != null && v != null;
    imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
}

@Umesh Maharjan 2018-10-09 10:38:06

 fun hideKeyboard(appCompatActivity: AppCompatActivity) {
        val view = appCompatActivity.currentFocus
        val imm = appCompatActivity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }

@bala 2018-10-09 05:57:21

Try this in Kotlin

 private fun hideKeyboard(){
    val imm = activity!!.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(activity!!.currentFocus!!.windowToken, 0)
}

Try this in Java

 private void hideKeyboard(){
  InputMethodManager imm =(InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
  imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}

@mr5 2018-09-25 02:05:08

For Xamarin.Android:

public void HideKeyboard()
{
    var imm = activity.GetSystemService(Context.InputMethodService).JavaCast<InputMethodManager>();
    var view = activity.CurrentFocus ?? new View(activity);
    imm.HideSoftInputFromWindow(view.WindowToken, HideSoftInputFlags.None);
}

@Ready Android 2018-08-08 07:22:29

Actually, always Android authority is giving new updates but they are not handling their old drawbacks which all Android developers face in their development this should be handled by Android authority by default, on changing focus from EditText should hide/show soft input keyboard option. But sorry about that, they are not managing. Ok, leave it.

Below are the solutions to show/hide/toggle a keyboard option in Activity or Fragment.

Show keyboard for the view:

/**
 * open soft keyboard.
 *
 * @param context
 * @param view
 */
public static void showKeyBoard(Context context, View view) {
    try {
        InputMethodManager keyboard = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        keyboard.showSoftInput(view, 0);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Show keyboard with Activity context:

/**
 * open soft keyboard.
 *
 * @param mActivity context
 */
public static void showKeyBoard(Activity mActivity) {
    try {
        View view = mActivity.getCurrentFocus();
        if (view != null) {
            InputMethodManager keyboard = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
            keyboard.showSoftInputFromInputMethod(view.getWindowToken(), InputMethodManager.SHOW_FORCED);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Show keyboard with Fragment context:

/**
 * open soft keyboard.
 *
 * @param mFragment context
 */
public static void showKeyBoard(Fragment mFragment) {
    try {
        if (mFragment == null || mFragment.getActivity() == null) {
            return;
        }
        View view = mFragment.getActivity().getCurrentFocus();
        if (view != null) {
            InputMethodManager keyboard = (InputMethodManager) mFragment.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            keyboard.showSoftInputFromInputMethod(view.getWindowToken(), InputMethodManager.SHOW_FORCED);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Hide keyboard for the view:

/**
 * close soft keyboard.
 *
 * @param context
 * @param view
 */
public static void hideKeyBoard(Context context, View view) {
    try {
        InputMethodManager keyboard = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        keyboard.hideSoftInputFromWindow(view.getWindowToken(), 0);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Hide keyboard with Activity context:

/**
 * close opened soft keyboard.
 *
 * @param mActivity context
 */
public static void hideSoftKeyboard(Activity mActivity) {
    try {
        View view = mActivity.getCurrentFocus();
        if (view != null) {
            InputMethodManager inputManager = (InputMethodManager) mActivity.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Hide keyboard with Fragment context:

/**
 * close opened soft keyboard.
 *
 * @param mFragment context
 */
public static void hideSoftKeyboard(Fragment mFragment) {
    try {
        if (mFragment == null || mFragment.getActivity() == null) {
            return;
        }
        View view = mFragment.getActivity().getCurrentFocus();
        if (view != null) {
            InputMethodManager inputManager = (InputMethodManager) mFragment.getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Toggle Keyboard:

/**
 * toggle soft keyboard.
 *
 * @param context
 */
public static void toggleSoftKeyboard(Context context) {
    try {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

@Rishabh Saxena 2018-09-03 20:34:39

When you want to hide keyboard manually on the action of button click:

/**
 * Hides the already popped up keyboard from the screen.
 *
 */
public void hideKeyboard() {
    try {
        // use application level context to avoid unnecessary leaks.
        InputMethodManager inputManager = (InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        assert inputManager != null;
        inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

When you want to hide keyboard where ever you click on screen except edittext Override this method in your activity:

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    View view = getCurrentFocus();
    if (view != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && view instanceof EditText && !view.getClass().getName().startsWith("android.webkit.")) {
        int scrcoords[] = new int[2];
        view.getLocationOnScreen(scrcoords);
        float x = ev.getRawX() + view.getLeft() - scrcoords[0];
        float y = ev.getRawY() + view.getTop() - scrcoords[1];
        if (x < view.getLeft() || x > view.getRight() || y < view.getTop() || y > view.getBottom())
            ((InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow((this.getWindow().getDecorView().getApplicationWindowToken()), 0);
    }
    return super.dispatchTouchEvent(ev);
}

@Dmitry 2018-09-07 02:52:11

To show keyboard on application start:

        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN | WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
        view.requestFocus();
        new Handler().postDelayed(new Runnable() {
            public void run() {
                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
            }
        }, 1000);

@jBegera 2018-09-03 14:21:29

I'm using following Kotlin Activity extensions:

/**
 * Hides soft keyboard if is open.
 */
fun Activity.hideKeyboard() {
    currentFocus?.windowToken?.let {
        (getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager?)
                ?.hideSoftInputFromWindow(it, InputMethodManager.HIDE_NOT_ALWAYS)
    }
}

/**
 * Shows soft keyboard and request focus to given view.
 */
fun Activity.showKeyboard(view: View) {
    view.requestFocus()
    currentFocus?.windowToken?.let {
        (getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager?)
                ?.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT)
    }
}

@Qamar 2018-08-16 04:52:26

In Kotlin

fun hideKeyboard(activity: BaseActivity) {
        val view = activity.currentFocus?: View(activity)
        val imm = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }

@Jedsada Tiwongvorakul 2018-07-23 02:32:40

you can create Extension function for any View

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

Example use with Activity

window.decorView.hideKeyboard();

Example use with View

etUsername.hideKeyboard();

Happy Coding...

@Daniel Beltrami 2018-05-30 19:06:55

Very simple way

I do this in all my projects, and work like a dream. In your declarations layout.xml just add this single line:

android:focusableInTouchMode="true"

Full code example:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:focusableInTouchMode="true">

    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

    </ListView>

</android.support.constraint.ConstraintLayout>

@Dika 2018-07-22 14:00:57

thank you! this is indeed the simplest way

Related Questions

Sponsored Content

46 Answered Questions

[SOLVED] Is there a unique Android device ID?

43 Answered Questions

20 Answered Questions

[SOLVED] How to hide underbar in EditText

11 Answered Questions

[SOLVED] Close/hide the Android Soft Keyboard with Kotlin

4 Answered Questions

[SOLVED] Programmatically Hide/Show Android Soft Keyboard

6 Answered Questions

77 Answered Questions

11 Answered Questions

[SOLVED] Proper use cases for Android UserManager.isUserAGoat()?

18 Answered Questions

[SOLVED] How to align views at the bottom of the screen?

19 Answered Questions

[SOLVED] Android: Force EditText to remove focus?

Sponsored Content