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?
Related Questions
Sponsored Content
41 Answered Questions
[SOLVED] Is there a unique Android device ID?
- 2010-05-07 00:47:28
- Tyler
- 867487 View
- 2463 Score
- 41 Answer
- Tags: android uniqueidentifier
13 Answered Questions
[SOLVED] Proper use cases for Android UserManager.isUserAGoat()?
- 2012-11-14 08:34:01
- Ovidiu Latcu
- 285211 View
- 3311 Score
- 13 Answer
- Tags: java android usermanager
7 Answered Questions
[SOLVED] Close/hide the Android Soft Keyboard with Kotlin
- 2017-01-22 11:32:55
- Eugene Trifonov
- 11846 View
- 9 Score
- 7 Answer
- Tags: android android-softkeyboard kotlin
4 Answered Questions
[SOLVED] Android: how to make keyboard enter button say "Search" and handle its click?
- 2010-07-08 15:36:41
- Ricket
- 144551 View
- 333 Score
- 4 Answer
- Tags: android android-softkeyboard
77 Answered Questions
[SOLVED] Why is the Android emulator so slow? How can we speed up the Android emulator?
- 2009-10-12 11:45:53
- Andrie
- 1001106 View
- 3224 Score
- 77 Answer
- Tags: android performance android-emulator genymotion qemu
16 Answered Questions
[SOLVED] How to hide underbar in EditText
- 2012-12-20 15:36:14
- Peri Hartman
- 226288 View
- 364 Score
- 16 Answer
- Tags: android textview android-edittext
18 Answered Questions
[SOLVED] How to align views at the bottom of the screen?
- 2010-03-05 13:04:23
- gav
- 477566 View
- 607 Score
- 18 Answer
- Tags: android xml user-interface android-layout
41 Answered Questions
[SOLVED] Strange out of memory issue while loading an image to a Bitmap object
- 2009-01-25 11:23:37
- Chrispix
- 582091 View
- 1162 Score
- 41 Answer
- Tags: android image bitmap out-of-memory android-bitmap
4 Answered Questions
[SOLVED] Programmatically Hide/Show Android Soft Keyboard
- 2011-08-26 05:16:44
- Krishnabhadra
- 250874 View
- 222 Score
- 4 Answer
- Tags: java android hide show soft-keyboard
1 Answered Questions
[SOLVED] Close/hide the Android Soft Keyboard on activity state onStop
- 2014-06-03 07:07:57
- Trần Đức Tâm
- 3287 View
- 8 Score
- 1 Answer
- Tags: android android-softkeyboard android-input-method
30 comments
@Ambilpura Sunil Kumar 2019-02-16 11:22:15
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.
}
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...@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.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
@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, theEditText
retains focus and the keyboard is hidden. Then when you tap theEditText
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.
@Xander 2013-03-11 18:26:52
@sebrock Works fine here on 4.1.1 HTC One X
@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()
thenInputMethodManager.HIDE_IMPLICIT_ONLY
even works on4.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 anactionId != 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()
intomyEditText.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 value0
@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, callingfocused.clearFocus()
, and theninputMethodManager.hideSoftInputFromWindow(focused.getWindowToken(), 0)
(with clear flags).@Lisa Anne 2015-09-10 10:42:09
Need to clear focus on the edittext!
@naXa 2015-09-11 13:22:22
@LisaAnne why??
@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_METHOD_SERVICE); imm.hideSoftInputFromWindow(focused.getWindowToken(), 0); }
@Bron Davies 2015-12-23 20:08:20
use
Handler h = new Handler(); h.postDelayed(runnable, 0);
where therunnable
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.WindowToken, HideSoftInputFlags.NotAlways);
@Paul Mathew 2018-03-22 10:44:59
after so many trial and error methods , this one worked like a charm. thanks man
@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
@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:
For Fragment:
Now you can simple call in your Fragment or Activity:
@Sreedev R 2012-05-04 04:02:00
@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).
@Lazy 2015-08-27 22:16:52
@ymerdrengene You are right, I had to delete it too.
@CoolMind 2018-09-19 14:28:11
Probably
input.getContext().getSystemService(Context.INPUT_METHOD_SERVICE)
.@CoolMind 2018-11-28 10:56:21
I removed
input.setInputType(0);
from this code. It changed a keyboard behaviour andinputType
for theEditText
.@Bruno Ribeiro 2019-02-01 04:55:17
perfect, these code works for me, thanks.
@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:
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 theInputMethodManager
to hide the keyboard. OK, fine, this is Android's API to the keyboard. BUT! You are required to have aContext
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 anyContext
. or And FAR worse, the IMM requires that you specify whatView
(or even worse, whatWindow
) 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 aView
or aWindow
.I have created a static utility method which can do the job VERY solidly, provided you call it from an
Activity
.Be aware that this utility method ONLY works when called from an
Activity
! The above method callsgetCurrentFocus
of the targetActivity
to fetch the proper window token.But suppose you want to hide the keyboard from an
EditText
hosted in aDialogFragment
? You can't use the method above for that:This won't work because you'll be passing a reference to the
Fragment
's hostActivity
, which will have no focused control while theFragment
is shown! Wow! So, for hiding the keyboard from fragments, I resort to the lower-level, more common, and uglier: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 yourActivity
. It naturally follows that the InputMethod (typically the soft keyboard) will respond to the focus event by showing itself. ThewindowSoftInputMode
attribute inAndroidManifest.xml
, when set tostateAlwaysHidden
, 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/orfocusableInTouchMode="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 calledignoreInitialFocus
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:
Given a fragment
fragment
as a parameter:Starting from your content body:
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
@Tina 2014-09-09 11:49:18
Thanks a lot for the thorough answer. Eloquent enough for a beginner to come with a good understanding of the soft keyboard. I wanted to hide/show keyboard from fragment and this was the most reasonable answer I found.
@Rameez Hussain 2014-09-10 07:37:06
Good and useful answer. It was one of those extremely rare posts on StackOverflow that are a pleasure to read.
@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 inhide_keyboard_from()
method? Is it typically anEditText
?@rmirabelle 2015-04-20 18:30:54
@AlexanderFarber yes, typically an
EditText
, but I believe any visibleView
will work (e.g.TextView
), since theView
is only used to derive a window token (the thing to hide the keyboard from). Also, I believe theView
should come from the hostActivity
rather than theFragment
@McX 2015-06-11 16:09:10
@rmirabelle In a
Fragment
it seems that you can usegetActivity().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();
@Amir Ziarati 2017-10-19 06:41:29
one upvote for being impolite to Android bad designed APIs :/ "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"
@Mark Yisri 2017-12-21 23:49:19
I upvoted this for it's useful information and the extremely humorous language. If only more answers were written this way...
@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
@hossein hatami 2018-07-09 15:24:21
I like it.......
@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
@Christopher Mills 2018-09-30 06:14:18
Google just got served.
@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. ;-)
@user1765048 2012-11-20 14:05:39
sometimes all you want is the enter button to fold the
keyboard
give theEditText
box you have the attributethis 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 includeandroid:singleLine="true"
@Rajneesh Shukla 2018-10-31 05:55:52
Call this method to hide the soft keyboard
@Janusz Hain 2018-03-07 09:01:13
I have written small extension for Kotlin if anyone interested, didn't test it much tho:
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
@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) :
2 - Then call it in any activity you needed it :
@Coldfin Lab 2018-10-16 06:47:55
@Khemraj 2018-10-01 09:54:22
Here are both hide & show methods.
Kotlin
Java
@Umesh Maharjan 2018-10-09 10:38:06
@bala 2018-10-09 05:57:21
Try this in Kotlin
Try this in Java
@mr5 2018-09-25 02:05:08
For Xamarin.Android:
@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:
Show keyboard with Activity context:
Show keyboard with Fragment context:
Hide keyboard for the view:
Hide keyboard with Activity context:
Hide keyboard with Fragment context:
Toggle Keyboard:
@Rishabh Saxena 2018-09-03 20:34:39
When you want to hide keyboard manually on the action of button click:
When you want to hide keyboard where ever you click on screen except edittext Override this method in your activity:
@Dmitry 2018-09-07 02:52:11
To show keyboard on application start:
@jBegera 2018-09-03 14:21:29
I'm using following Kotlin Activity extensions:
@Qamar 2018-08-16 04:52:26
In Kotlin
@Jedsada Tiwongvorakul 2018-07-23 02:32:40
you can create Extension function for any View
Example use with Activity
Example use with View
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:Full code example:
@Dika 2018-07-22 14:00:57
thank you! this is indeed the simplest way
@Jeyavel 2009-12-04 10:01:27
Please try this below code in
onCreate()
@Spike Williams 2010-04-17 05:50:54
This method works as a means of getting around the "can't hide the soft keyboard" bug in 2.0 and 2.1 as described in code.google.com/p/android/issues/detail?id=7115 ... the hideSoftInputFromWindow method listed above did not work when I tried it, but editView.setInputType(0) did.
@Bostone 2010-10-11 20:49:27
This is legit per Javadoc (not a hack) though I would rewrite the method as
editView.setInputType(InputType.TYPE_NULL);
@Tirtha 2012-01-11 10:32:12
this works, however, it hides the android:hint. i'm using Android 1.5
@nmxprime 2014-06-20 09:11:03
@Bostone This is not working for SearchView
@I'm_With_Stupid 2014-12-26 21:38:05
this is great for when you need to close the keyboard from a dialog, don't need to get an instance or anything and can assign this to all edit texts when user presses a button that closes the dialog
@Stefan Brendle 2016-08-08 18:51:20
It works, but it's also hiding the cursor. I need the cursor, but no system keyboard.
@Rafols 2018-04-05 08:11:12
Some kotlin code:
Hide keyboard from Activity:
@Harpreet 2018-03-28 12:37:43
If your application is targeting API Level 21 or more than there is a default method to use:
Make sure you have set below code in
EditText
XML tag.@Nadeem Bhat 2018-03-26 10:11:58
In Android to hide the Vkeyboard by InputMethodManage you can cal hideSoftInputFromWindow by passing in the token of the window containing your focused view.
By Calling editText.clearFocus() and then InputMethodManager.HIDE_IMPLICIT_ONLY even works
@Luke Sleeman 2013-04-06 13:20:49
I have spent more than two days working through all of the solutions posted in the thread and have found them lacking in one way or another. My exact requirement is to have a button that will with 100% reliability show or hide the on screen keyboard. When the keyboard is in its hidden state is should not re-appear, no matter what input fields the user clicks on. When it is in its visible state the keyboard should not disappear no matter what buttons the user clicks. This needs to work on Android 2.2+ all the way up to the latest devices.
You can see a working implementation of this in my app clean RPN.
After testing many of the suggested answers on a number of different phones (including froyo and gingerbread devices) it became apparent that android apps can reliably:
For me, temporarily hiding the keyboard is not enough. On some devices it will re-appear as soon as a new text field is focused. As my app uses multiple text fields on one page, focusing a new text field will cause the hidden keyboard to pop back up again.
Unfortunately item 2 and 3 on the list only work reliability when an activity is being started. Once the activity has become visible you cannot permanently hide or show the keyboard. The trick is to actually restart your activity when the user presses the keyboard toggle button. In my app when the user presses on the toggle keyboard button, the following code runs:
This causes the current activity to have its state saved into a Bundle, and then the activity is started, passing through an boolean which indicates if the keyboard should be shown or hidden.
Inside the onCreate method the following code is run:
If the soft keyboard should be shown, then the InputMethodManager is told to show the keyboard and the window is instructed to make the soft input always visible. If the soft keyboard should be hidden then the WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM is set.
This approach works reliably on all devices I have tested on - from a 4 year old HTC phone running android 2.2 up to a nexus 7 running 4.2.2. The only disadvantage with this approach is you need to be careful with handling the back button. As my app essentially only has one screen (its a calculator) I can override onBackPressed() and return to the devices home screen.
@rupps 2013-05-15 13:43:12
elaborate workaround, but i think it's just too much , to recreate thousands of objects just to hide the Keyboard. I dont know who designed the IMM for android, but it smells like a Windows APi. In my opinion, a good IME should have two methods: hide and show :-)
@Luke Sleeman 2013-05-20 11:35:55
Its all true, but my workaround does have one advantage - it always works! There is no other solution I could find that would always toggle the keyboard, regardless of of what fields in the UI have the focus, what the user has done to toggle and keyboard and what version of android they are running :-\
@rupps 2013-05-20 14:57:45
Man, I'm totally desperate to hide the keyboard. Tried thousands of things and noooone works. But your workaround is too much for me, I'd have to recreate like 10 fragments, initialize services, delete a lot of WeakReferences .... you know? the GC would just throw away like 25mb :S ... Still looking for a reliable way to do it :(
@rupps 2013-10-08 16:21:53
@Dmitry well it's not a hello world...it's a complex application for tablets. I refuse to totally unload it from memory just to hide a silly keyboard... Anyway I found something that works combining the thousand solutions proposed here :)
@Faxriddin Abdullayev 2018-01-15 08:03:00
Here are the best solutions
Solution 1) Set the inputType to “text”
This can also be done programmatically via. the method setInputType() (inherited from TextView).
Solution 2) Use the InputMethodManager.hideSoftInputFromWindow()
or
@uma 2017-12-20 12:17:52
you can simply add this code where you want to hide the soft keyboard"