How can I close/hide the Android soft keyboard programmatically?
Asked Answered
F

130

4346

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 when touching outside the keyboard. I assume that this is a simple piece of code, but where can I find an example of it?

Factorize answered 10/7, 2009 at 11:27 Comment(8)
What if you have only one EditText and several buttons, like check boxes and radios? The only place you need the keyboard is in the single EditText. How do you register to know that something else was chosen/clicked in order to hide the keyboard?Rabjohn
i feel stupid. I am unable to hide the keyboard on ICS. Tried all methods here and combinations of them. No way. The method to show it works, but I cant hide it no matter what windw token, hide flags, manifest settings or candles to any saints. On keyboard show I always see this: I/LatinIME( 396): InputType.TYPE_NULL is specified W/LatinIME( 396): Unexpected input class: inputType=0x00000000 imeOptions=0x00000000Joyous
/** * This method is used to hide soft keyboard. * @param activity */ public void hideSoftKeyboard(Activity activity) { InputMethodManager inputMethodManager = (InputMethodManager)activity.getSystemService(Activity.INPUT_METHOD_SERVICE); inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0); }Hoshi
this worked for meTwentyfourmo
Need to play with InputMethodManager with the INPUT_METHOD_SERVICE to handle soft keyboard like readyandroid.wordpress.com/show-hide-android-soft-keyboardEpperson
Are you serious with that? Can't simply hide the keybord at any point just if you want to? It doesn't mater if you have many buttons, or text, or a huge screen, to ask Android to hide keybord must be a single instruction :SSpooky
Try using InputMethodManager to handle the keyboard. Can try following this article. androidacademic.blogspot.com/2023/02/…Seyler
to do this physically on the device when the keyboard is showing you can just hit the back button. is that an option in your program? edit - lol this question is so old! my b!Anesthetize
A
2568

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


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

Albacore answered 10/7, 2009 at 11:27 Comment(9)
Why need getRootView() , why not getView() only?Putrescible
One liner: ((InputMethodManager)getContext().getSystemService(Activity.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(getView().getWindowToken(), 0);Creole
Recently we finally got an official, backwards compatible way to do thisUlphi
Finally there is an official way https://mcmap.net/q/36082/-how-can-i-close-hide-the-android-soft-keyboard-programmaticallyCrowl
I have one problem with this. The text inside the EditText field stays underlined as if the keyboard's suggestions were still active.Dolce
@Dolce sounds like the EditText is retaining focus. The ONLY way I know to remove focus from an input is to manually assign focus to anything else.Albacore
@SergeyChilingaryan It is not official and it is not working properly on some versions as you can see on the answer. On top of that, at least, one method has been deprecated now.Beaver
Hello, when the keyboard showed up on the screen I just went into the keyboard settings and unticked the "Show keyboard" box - that solved it for me. Hope it helpsBusboy
Be aware that this utility method ONLY works when called from an Activity! I save the top Activity onResume and onCreate into a global variable (kotlin): var myPageTop = WeakReference<ComponentActivity>(null) Then you can do whatever you want without passing context around. The best way to solve this kind of dependency problem is to use global variable.Osrock
B
4710

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 the menu).

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

Kotlin Syntax

// Only runs if there is a view that is currently focused
this.currentFocus?.let { view ->
    val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as? InputMethodManager
    imm?.hideSoftInputFromWindow(view.windowToken, 0)
}
Bijouterie answered 10/7, 2009 at 11:27 Comment(3)
now getSystemService() requires a Context and a serviceClass Class. For the context I can call requiredContext but what about for the serviceClass?Sulphurate
@Sulphurate I tried with Application.Context.getSystemService(), so I didn't need the serviceClass, but it doesn't workSpooky
Works well for me inside a Fragment using getActivity().getSystemService()...Cartomancy
A
2568

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


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

Albacore answered 10/7, 2009 at 11:27 Comment(9)
Why need getRootView() , why not getView() only?Putrescible
One liner: ((InputMethodManager)getContext().getSystemService(Activity.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(getView().getWindowToken(), 0);Creole
Recently we finally got an official, backwards compatible way to do thisUlphi
Finally there is an official way https://mcmap.net/q/36082/-how-can-i-close-hide-the-android-soft-keyboard-programmaticallyCrowl
I have one problem with this. The text inside the EditText field stays underlined as if the keyboard's suggestions were still active.Dolce
@Dolce sounds like the EditText is retaining focus. The ONLY way I know to remove focus from an input is to manually assign focus to anything else.Albacore
@SergeyChilingaryan It is not official and it is not working properly on some versions as you can see on the answer. On top of that, at least, one method has been deprecated now.Beaver
Hello, when the keyboard showed up on the screen I just went into the keyboard settings and unticked the "Show keyboard" box - that solved it for me. Hope it helpsBusboy
Be aware that this utility method ONLY works when called from an Activity! I save the top Activity onResume and onCreate into a global variable (kotlin): var myPageTop = WeakReference<ComponentActivity>(null) Then you can do whatever you want without passing context around. The best way to solve this kind of dependency problem is to use global variable.Osrock
M
855

Also useful for hiding the soft-keyboard is:

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

This can be used to suppress the soft-keyboard until the user actually touches the editText View.

Magocsi answered 10/7, 2009 at 11:27 Comment(2)
This was the only one that worked for in 2020. I have a edit text on the main activity and don't want the keyboard to come up when starting the app.Chervonets
Try using InputMethodManager to handle the keyboard. Can try following this article. androidacademic.blogspot.com/2023/02/…Seyler
P
389

I got one more solution to hide keyboard:

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

Here pass HIDE_IMPLICIT_ONLY at the position of showFlag and 0 at the position of hiddenFlag. It will forcefully close soft Keyboard.

Plasm answered 10/7, 2009 at 11:27 Comment(3)
You're using a hide flag in the showflags parameter. This only works because the constants use the same integers. Example using the correct flagsMethodize
@Mark: Because the method is called "toggleSoftInput", not "hideSoftInput" :)Decumbent
This doesn't work correctly. It some times shows the keyboard.Thoracotomy
R
170

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);
    }
}
Regazzi answered 10/7, 2009 at 11:27 Comment(0)
J
166

Please try this below code in onCreate()

EditText edtView = (EditText) findViewById(R.id.editTextConvertValue);
edtView.setInputType(InputType.TYPE_NULL);
Jacobin answered 10/7, 2009 at 11:27 Comment(5)
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.Patentor
This is legit per Javadoc (not a hack) though I would rewrite the method as editView.setInputType(InputType.TYPE_NULL);Lowell
this works, however, it hides the android:hint. i'm using Android 1.5Lordan
It works, but it's also hiding the cursor. I need the cursor, but no system keyboard.Johansen
Second part of the answer was copied from another answer. Revision was rolled back.Clem
P
157

Update: I don't know why this solution is not work any more ( I just tested on Android 23). Please use the solution of Saurabh Pareek instead. Here it is:

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

Old answer:

//Show soft-keyboard:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
//hide keyboard :
 getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Patter answered 10/7, 2009 at 11:27 Comment(7)
Where should i place this code? I've tried to paste getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN); in onCreate() but the keyboard is never hiddenApex
does not work, tested in radioGroup.setOnCheckedChangeListener, API 23Ecumenicist
If you look closer, InputMethodManager.HIDE_IMPLICIT_ONLY and InputMethodManager.SHOW_IMPLICIT have the same value, which is "1", so there is no difference between these calls. => not workingChinchy
if calling imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); then keyboard will show on screen :) Best implementation is: github.com/ravindu1024/android-keyboardlistener Shame on Android SDKActivist
I don't know why this solution is not work any more - because it's Android, everything will be able to change, maybe partly of bad design... We write carelessly, then we strike out all and rewrite everything.Chancechancel
Working, but actually makes the keyboard VISIBLE on almost all SAMSUNG devices :) I love Android.Behaviorism
Check this out for answer medium.com/p/a111cffb8704Seyler
A
104
protected void hideSoftKeyboard(EditText input) {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(input.getWindowToken(), 0);    
}
Abagael answered 10/7, 2009 at 11:27 Comment(3)
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).Galibi
Probably input.getContext().getSystemService(Context.INPUT_METHOD_SERVICE).Chromosphere
I removed input.setInputType(0); from this code. It changed a keyboard behaviour and inputType for the EditText.Chromosphere
C
88

If all the other answers here don't work for you as you would like them to, there's another way of manually controlling the keyboard.

Create a function with that will manage some of the EditText's properties:

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

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

Then, make sure that onFocus of the EditText you open/close the keyboard:

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

Now, whenever you want to open the keyboard manually call:

setEditTextFocus(true);

And for closing call:

setEditTextFocus(false);
Charleycharlie answered 10/7, 2009 at 11:27 Comment(3)
I got 'Cannot resolve symbol context', on 7th and 10th line of second block of code.Corkscrew
Use getContext() insteadCharleycharlie
Context context = View.getContext();Melodic
M
73

Saurabh Pareek has the best answer so far.

Might as well use the correct flags, though.

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

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

Example of real use

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

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

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

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

    /* parameters valid ... */
}
Methodize answered 10/7, 2009 at 11:27 Comment(0)
S
66

from so searching, here I found an answer that works for me

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

// Hide soft-keyboard:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Skill answered 10/7, 2009 at 11:27 Comment(0)
S
64

The short answer

In your OnClick listener call the onEditorAction of the EditText with IME_ACTION_DONE

button.setOnClickListener(new OnClickListener() {

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

The drill-down

I feel this method is better, simpler and more aligned with Android's design pattern. In the simple example above (and usually in most of the common cases) you'll have an EditText that has/had focus and it also usually was the one to invoke the keyboard in the first place (it is definitely able to invoke it in many common scenarios). In that same way, it should be the one to release the keyboard, usually that can be done by an ImeAction. Just see how an EditText with android:imeOptions="actionDone" behaves, you want to achieve the same behavior by the same means.


Check this related answer

Shawana answered 10/7, 2009 at 11:27 Comment(0)
D
50

This should work:

public class KeyBoard {

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

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

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

KeyBoard.toggle(activity);
Divulgence answered 10/7, 2009 at 11:27 Comment(3)
@YoushaAleayoub yes it will. KeyBoard.toggle(fragment.getActivity())Divulgence
@slinden77, lol, I'm talking about your Answer... not this one you have commented. So that answer still WONT work.Sardis
@YoushaAleayoub uhm yes it will. The original question doesn't mention fragments, you are the one who mentioned fragments. So my answer is perfectly valid. To use it with fragments, call the method differently from a Fragment, like a commented. Learn how to use methods please and then come back. You're confusing people with your silly repliesDivulgence
C
49

Thank God it’s officially supported after 11 years.

First add dependency implementation 'androidx.core:core-ktx:1.7.0' to app gradle.

Then get InsetsController from ViewCompat or WindowCompat class.

Finally use hide() and show() function of InsetsController

Add support for Dialog. Available in BottomSheetDialog. @Rondev. Using a safer way to get activity instead of directly cast from context.

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.ContextWrapper
import android.view.View
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment

fun View.showKeyboard() = ViewCompat.getWindowInsetsController(this)?.show(WindowInsetsCompat.Type.ime())
fun View.hideKeyboard() = ViewCompat.getWindowInsetsController(this)?.hide(WindowInsetsCompat.Type.ime())

fun Dialog.showKeyboard() = window?.decorView?.showKeyboard()
fun Dialog.hideKeyboard() = window?.decorView?.hideKeyboard()

fun Context.showKeyboard() = getActivity()?.showKeyboard()
fun Context.hideKeyboard() = getActivity()?.hideKeyboard()

fun Fragment.showKeyboard() = activity?.showKeyboard()
fun Fragment.hideKeyboard() = activity?.hideKeyboard()

fun Activity.showKeyboard() = WindowCompat.getInsetsController(window, window.decorView)?.show(WindowInsetsCompat.Type.ime())
fun Activity.hideKeyboard() = WindowCompat.getInsetsController(window, window.decorView)?.hide(WindowInsetsCompat.Type.ime())

fun Context.getActivity(): Activity? {
    return when (this) {
        is Activity -> this
        is ContextWrapper -> this.baseContext.getActivity()
        else -> null
    }
}

Old anwser below

Here is the simple project on github

import android.app.Activity
import android.app.Dialog
import android.content.Context
import android.content.ContextWrapper
import android.view.View
import androidx.core.view.ViewCompat
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment

fun View.showKeyboard() = ViewCompat.getWindowInsetsController(this)?.show(WindowInsetsCompat.Type.ime())
fun View.hideKeyboard() = ViewCompat.getWindowInsetsController(this)?.hide(WindowInsetsCompat.Type.ime())

fun Dialog.showKeyboard() = window?.decorView?.showKeyboard()
fun Dialog.hideKeyboard() = window?.decorView?.hideKeyboard()

fun Context.showKeyboard() = getActivity()?.showKeyboard()
fun Context.hideKeyboard() = getActivity()?.hideKeyboard()

fun Fragment.showKeyboard() = activity?.showKeyboard()
fun Fragment.hideKeyboard() = activity?.hideKeyboard()

fun Activity.showKeyboard() = WindowCompat.getInsetsController(window, window.decorView)?.show(WindowInsetsCompat.Type.ime())
fun Activity.hideKeyboard() = WindowCompat.getInsetsController(window, window.decorView)?.hide(WindowInsetsCompat.Type.ime())

fun Context.getActivity(): Activity? {
    return when (this) {
        is Activity -> this
        is ContextWrapper -> this.baseContext.getActivity()
        else -> null
    }
}
Crowl answered 10/7, 2009 at 11:27 Comment(7)
Requires API level 31Thumbsdown
@Thumbsdown For compatibility, use WindowCompat and WindowInsetsControllerCompat. You'll need to upgrade your gradle dependency for androidx.core to at least 1.6.0-alpha03 so that there will be support on SDK < 30.Crowl
@Thumbsdown take a look at the sample project github.com/sergchil/KeyboardTestCrowl
Unfortunately I couldn't get the hide function to work inside a BottomSheetDialogFragmentDex
@Dex That is because dialogs run in their own window. Instead, you can do dialog?.window instead.Essene
getWindowInsetsController is deprecatedCannular
developer.android.com/reference/androidx/core/view/… says "This method is deprecated. Prefer getInsetsController to explicitly specify the window (such as when the view is in a dialog)." Which means that we're back to specifying a window as well as a view, even though we may be in a place where we don't know or care about either one.Danidania
H
49

I'm using a custom keyboard to input an Hex number so I can't have the IMM keyboard show up...

In v3.2.4_r1 setSoftInputShownOnFocus(boolean show) was added to control weather or not to display the keyboard when a TextView gets focus, but its still hidden so reflection must be used:

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

For older versions, I got very good results (but far from perfect) with a OnGlobalLayoutListener, added with the aid of a ViewTreeObserver from my root view and then checking if the keyboard is shown like this:

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

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

This last solution may show the keyboard for a split second and messes with the selection handles.

When in the keyboard enters full screen, onGlobalLayout isn't called. To avoid that, use TextView#setImeOptions(int) or in the TextView XML declaration:

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

Update: Just found what dialogs use to never show the keyboard and works in all versions:

getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
        WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
Hollowell answered 10/7, 2009 at 11:27 Comment(2)
Cool solution, however, if your front activity is not fullscreen, the keyboard is visible behind it. Also the keyboard's cursor movement aid is also still visible. And it's not skinnable.Lave
I second that. Of all the possible ways only the getWindow().setFlags() method works, at least on stock Android 5.1. Note that setSoftInputShownOnFocus() is now setShowSoftInputOnFocus() and no longer hidden but does not work, at least not when the user touches the field.Mouldon
C
38
public void setKeyboardVisibility(boolean show) {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    if(show){
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
    }else{
        imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),0);
    }
}
Continuum answered 10/7, 2009 at 11:27 Comment(0)
U
36

Now, almost 12 years later, we finally have an official, backwards compatible way to do this with AndroidX Core 1.5+:

fun View.hideKeyboard() = ViewCompat.getWindowInsetsController(this)
    ?.hide(WindowInsetsCompat.Type.ime())

or specifically for Fragment:

fun Fragment.hideKeyboard() = ViewCompat.getWindowInsetsController(requireView())
    ?.hide(WindowInsetsCompat.Type.ime())
Ulphi answered 10/7, 2009 at 11:27 Comment(8)
Well would you look at that! Of course, it had to involve yet another API (window insets controller vs input method manager), but hey, at least the word 'hide' is there.Albacore
If you want to hide the keyboard but only have a reference to the Activity, which view should you use? window.decorView? Before, you would get the windowToken with currentFocus?.windowToken and then use InputMethodManager.hideSoftInputFromWindow(windowToken, 0)Rotenone
@Mark, good question! Testing shows that window.decorView does not work on API 25-29: ViewCompat.getWindowInsetsController() returns null. currentFocus has a similar problem on API 30. But you can use any view in your layout, e.g. its root view. For hiding keyboard it works, but for showing keyboard you might be better off with some EditText: WindowInsetsControllerCompat.show() uses it to request focus.Ulphi
Thanks @Ulphi So how about using currentFocus pre-30, and window.decorView 30+?Rotenone
That might work, but in any case you will have to test it thoroughly. Behavior might depend on device manufacturer, your specific widgets layout and other factors. For example, on one of my devices this method to show keyboard works well with GBoard, but disables SwiftKey completely. This is Android. :(Ulphi
@Ulphi good to know thanks. So it sounds like it would be better to use a View in the activity's View hierarchy (usually I have access to SomeBinding.root). From a Fragment, just use view?.hideKeyboard(). However, I'm not seeing any benefit over using context.getSystemService<InputMethodManager>()?.hideSoftInputFromWindow(windowToken, 0)Rotenone
I've rolled back changes by @hb0 because ViewCompat already includes that SDK version check. Even its name implies "backwards compatibility". ;)Ulphi
In Kotlin?Equivalency
E
33

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:

  1. Temporarily hide the keyboard. It will re-appear again when a user focuses a new text field.
  2. Show the keyboard when an activity starts and set a flag on the activity indicating that they keyboard should always be visible. This flag can only be set when an activity is initialising.
  3. Mark an activity to never show or allow the use of the keyboard. This flag can only be set when an activity is initialising.

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:

private void toggleKeyboard(){

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

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

        startActivity(i);
    }
}

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(bundle.getBoolean(SHOW_KEYBOARD)){
    ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).showSoftInput(newEquationText,0);
    getWindow().setSoftInputMode(LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
else{
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
            WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM);
}

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.

Euchology answered 10/7, 2009 at 11:27 Comment(4)
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 :-)Joyous
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 :-\Euchology
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 :(Joyous
@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 :)Joyous
P
31

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

if (getCurrentFocus() != null) {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
Pentatomic answered 10/7, 2009 at 11:27 Comment(0)
S
26

Thanks to this SO answer, I derived the following which, in my case, works nicely when scrolling through the the fragments of a ViewPager...

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

private void showKeyboard() {   
    // Check if no view has focus:
    View view = this.getCurrentFocus();
    if (view != null) {
        InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT);
    }
}
Scimitar answered 10/7, 2009 at 11:27 Comment(0)
R
22

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

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

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

and to get the context fetch it from constructor:)

public View/RelativeLayout/so and so (Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    this.context = context;
    init();
}
Raillery answered 10/7, 2009 at 11:27 Comment(0)
A
21

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

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

I put "back button" in quotes, since the above doesn't trigger the onBackPressed() for the Activity in question. It just closes the keyboard.

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

Apothecary answered 10/7, 2009 at 11:27 Comment(0)
C
18

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

InputMethodManager imm = GetSystemService (Context.InputMethodService) as InputMethodManager;
if (imm != null)
    imm.HideSoftInputFromWindow (searchbox.WindowToken , 0);
Chuckchuckfull answered 10/7, 2009 at 11:27 Comment(1)
What is searchbox in the snippet?Tunic
V
17

This worked for me for all the bizarre keyboard behavior

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

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

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

protected void hideKeyboard() {
    if (!isKeyboardVisible())
        return;
    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    View view = getCurrentFocus();
    if (view == null) {
        if (inputMethodManager.isAcceptingText())
            inputMethodManager.toggleSoftInput(InputMethodManager.HIDE_NOT_ALWAYS, 0);
    } else {
        if (view instanceof EditText)
            ((EditText) view).setText(((EditText) view).getText().toString()); // reset edit text bug on some keyboards bug
        inputMethodManager.hideSoftInputFromInputMethod(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
}
Villainage answered 10/7, 2009 at 11:27 Comment(1)
What is mRootView?Eliga
Q
16

Kotlin version via an extension function

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

ExtensionFunctions.kt

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:

editText.hideKeyboard()
Quoth answered 10/7, 2009 at 11:27 Comment(0)
D
16

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

/**
 * This method is used to hide keyboard
 * @param activity
 */
public static void hideKeyboardFrom(Activity activity) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
Dyslalia answered 10/7, 2009 at 11:27 Comment(1)
You didn't check whether activity.getCurrentFocus() was null, it could well be if the keyboard was actually not visibleEstivate
D
15

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

<activity
            android:name=".ui.activity.MainActivity"
            android:label="@string/mainactivity"
            android:windowSoftInputMode="stateHidden"/>
Dewey answered 10/7, 2009 at 11:27 Comment(0)
N
15

Just use this optimized code in your activity:

if (this.getCurrentFocus() != null) {
    InputMethodManager inputManager = (InputMethodManager) this.getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
Nahshun answered 10/7, 2009 at 11:27 Comment(0)
A
14

Works like magic touch every time

private void closeKeyboard() {
    InputMethodManager inputManager = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

}

private void openKeyboard() {
    InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
    if(imm != null){
        imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
    }
}
Ashtoreth answered 10/7, 2009 at 11:27 Comment(0)
T
14

For Open Keyboard :

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(edtView, InputMethodManager.SHOW_IMPLICIT);

For Close/Hide Keyboard :

 InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
 imm.hideSoftInputFromWindow(edtView.getWindowToken(), 0);
Tarentarentum answered 10/7, 2009 at 11:27 Comment(0)
G
14

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

public static void hideKeyboard( Activity activity ) {
    InputMethodManager imm = (InputMethodManager)activity.getSystemService( Context.INPUT_METHOD_SERVICE );
    View f = activity.getCurrentFocus();
    if( null != f && null != f.getWindowToken() && EditText.class.isAssignableFrom( f.getClass() ) )
        imm.hideSoftInputFromWindow( f.getWindowToken(), 0 );
    else 
        activity.getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN );
}
Gentlemanfarmer answered 10/7, 2009 at 11:27 Comment(1)
This solution is better because you have not to control which EditText pass as a parameter to hideSoftInputFromWindow() method. It works great!!Stedfast
G
12

use this

this.getWindow().setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Granivorous answered 10/7, 2009 at 11:27 Comment(0)
L
12
public static void hideSoftKeyboard(Activity activity) {
    InputMethodManager inputMethodManager = (InputMethodManager)  activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}

after that call on onTouchListener:

findViewById(android.R.id.content).setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        Utils.hideSoftKeyboard(activity);
        return false;
    }
});
Lilla answered 10/7, 2009 at 11:27 Comment(1)
Try this as well - this worked for me: InputMethodManager imm = ((InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE)); imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);Massproduce
O
11

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

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

public static void hideSoftKeyboard(View view) {
    if (view != null) {
        InputMethodManager inputManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (inputManager != null) {
            inputManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
}
Optical answered 10/7, 2009 at 11:27 Comment(0)
M
11

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

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

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

/**
 * Force hide softKeyboard.
 */
public static void forceHide(@NonNull Activity activity, @NonNull EditText editText) {
    if (activity.getCurrentFocus() == null || !(activity.getCurrentFocus() instanceof EditText)) {
        editText.requestFocus();
    }
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
    activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
}
Makell answered 10/7, 2009 at 11:27 Comment(0)
A
11

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

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

mSearchView.clearFocus();
mSearchView.setFocusable(false);
Awoke answered 10/7, 2009 at 11:27 Comment(3)
Very clever. If the user wants another search, just click search again.Methodize
SearchView does not have a clearFocus() in the Android API pages, so this did not work for me, but another solution did (see my answer below).Hub
@Noni A, #7409788Sardis
C
8

Just call the below method. It will hide your keyboard if it’s 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) {
    }
}
Craw answered 10/7, 2009 at 11:27 Comment(0)
L
8

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.

Laszlo answered 10/7, 2009 at 11:27 Comment(1)
in my case, in addition to android:imeOptions="actionDone" also needed to include android:singleLine="true"Ligation
K
8

You could also look into using setImeOption on the EditText.

I just had a very simular situation where my layout contained an EditText and a search button. When I discovered I could just set the ime option to "actionSearch" on my editText, I realized I didn't even need a search button anymore. The soft keyboard (in this mode) has a search icon, which can be used to kick off the search (and the keyboard closes itself as you would expect).

Keddah answered 10/7, 2009 at 11:27 Comment(1)
is there some trick to making the keyboad auto close in this method? it's not doing so on jellybean. the edittext loses focus, but the keyboard doesn't hide.Banky
B
7

So many of these answers are needlessly complex; here is a solution for Kotlin users to create a neat little extension function on the View class.

Create a basic Kotlin file (I've named mine KeyboardUtil.kt), and introduce the following:

fun View.hideKeyboard() {
  val imm = ContextCompat.getSystemService(context, InputMethodManager::class.java) as InputMethodManager
  imm.hideSoftInputFromWindow(windowToken, 0)
}

Then, you can call this on any view to easily dismiss the keyboard. I use ViewBinding/DataBinding, and it works particularly well, for example:

fun submitForm() {
  binding.root.hideKeyboard()
  // continue now the keyboard is dismissed
}
Blowgun answered 10/7, 2009 at 11:27 Comment(0)
I
7

Using Android 10, we are going to get an amazing way to show and hide keyboards. Read the Release Notes - 1.5.0-alpha02. Now how to hide or show the keyboard:

val controller = view.windowInsetsController

// Show the keyboard
controller.show(Type.ime())
// Hide the keyboard
controller.hide(Type.ime())

Linking my own answer How to check visibility of software keyboard in Android? and an Amazing blog which includes more of this change (even more than it).

Islington answered 10/7, 2009 at 11:27 Comment(2)
what is import for Type?Nucleonics
@MichaelAbyzov This would be 'developer.android.com/reference/android/view/WindowInsets.Type', see more about the hide() method at 'developer.android.com/reference/kotlin/android/view/…'Islington
G
7

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)
    }
}
Garthgartner answered 10/7, 2009 at 11:27 Comment(0)
S
6

A Kotlin solution in a fragment

fun hideSoftKeyboard() {
        val view = activity?.currentFocus
        view?.let { v ->
            val imm =
                activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager // or context
            imm.hideSoftInputFromWindow(v.windowToken, 0)
        }
}

Check your manifest doesn't have this parameter associated with your activity:

android:windowSoftInputMode="stateAlwaysHidden"
Studnia answered 10/7, 2009 at 11:27 Comment(0)
C
6

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()
Crybaby answered 10/7, 2009 at 11:27 Comment(2)
instead of writing the same logic again just call activity?.hideKeyboard from your fragment implementationRossini
Btw, the fragment implementation doesn't work as stated by community wiki. To get the correct windowToken you'll have to call val windowToken = view?.rootView?.windowTokenRossini
B
6

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
Belvabelvedere answered 10/7, 2009 at 11:27 Comment(0)
L
6

this is Working..

Just Pass your current activity instance in the function

 public void isKeyBoardShow(Activity activity) {
    InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
    if (imm.isActive()) {
        imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0); // hide
    } else {
        imm.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY); // show
    }
}
Lamrert answered 10/7, 2009 at 11:27 Comment(0)
U
6

Try this

  • Simple you can call in your Activity

 public static void hideKeyboardwithoutPopulate(Activity activity) {
    InputMethodManager inputMethodManager =
            (InputMethodManager) activity.getSystemService(
                    Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(
            activity.getCurrentFocus().getWindowToken(), 0);
}

  • In your MainActivitiy call this

 hideKeyboardwithoutPopulate(MainActivity.this);

Undesigning answered 10/7, 2009 at 11:27 Comment(0)
D
6

If you want to hide keyboard using Java code, then use this:

  InputMethodManager imm = (InputMethodManager)this.getSystemService(Context.INPUT_METHOD_SERVICE);
  imm.hideSoftInputFromWindow(fEmail.getWindowToken(), 0);

Or if you want to hide the keyboard always, then use this in your AndroidManifest:

 <activity
 android:name=".activities.MyActivity"
 android:configChanges="keyboardHidden"  />
Drover answered 10/7, 2009 at 11:27 Comment(1)
The java code solution worked for me in a fragment when I replaced fEmail with the view that opened the keyboard. It worked on Samsung Galaxy Tab S2 running Android 5.1.1, Nexus 5 running 6.0.1, and an XT1032 running 5.1 (This is using the support libraries.)Blatherskite
L
6

In AndroidManifest.xml under <activity..> set android:windowSoftInputMode="stateAlwaysHidden"

Loreanloredana answered 10/7, 2009 at 11:27 Comment(0)
P
6

Sometime you can have an activity that contains a listview with rows that contains editText so you have to setup in manifest SOFT_INPUT_ADJUST_PAN then they keyboard shows up which is annoying.

The following workarround works if you place it at the end of onCreate

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
            }
        },100);
Pogge answered 10/7, 2009 at 11:27 Comment(0)
B
6

It works for me..

EditText editText=(EditText)findViewById(R.id.edittext1);

put below line of code in onClick()

editText.setFocusable(false);
editText.setFocusableInTouchMode(true);

here hide the keyboard when we click the Button and when we touch the EditText keyboard will be display.

(OR)

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Burgener answered 10/7, 2009 at 11:27 Comment(0)
V
5

In Kotlin, just use these two methods to show and hide the keyboard.

fun showKeyboard() =
    (context.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as? InputMethodManager)!!
        .toggleSoftInput(InputMethodManager.SHOW_FORCED, 0)

fun hideKeyboard(view: View) =
    (context.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE) as? InputMethodManager)!!
        .hideSoftInputFromWindow(view.windowToken, 0)

Here view is your current view.

Violaviolable answered 10/7, 2009 at 11:27 Comment(0)
J
5

Just add the following line in AndroidManifest in the specific activity.

<activity
    android:name=".MainActivity"
    android:screenOrientation="portrait"
    android:windowSoftInputMode="adjustPan"/>
Jocelyn answered 10/7, 2009 at 11:27 Comment(0)
S
5

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);
    }
}
Solan answered 10/7, 2009 at 11:27 Comment(0)
P
5

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);
}
Physicist answered 10/7, 2009 at 11:27 Comment(0)
M
5

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)
    }
Mecke answered 10/7, 2009 at 11:27 Comment(0)
E
5

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();
    }
}
Epperson answered 10/7, 2009 at 11:27 Comment(0)
A
4

For those looking for jetpack compose answer.

val keyboardController = LocalSoftwareKeyboardController.current

//for showing the keyboard
keyboardController?.show()
//for hiding the keyboard
keyboardController?.hide()
Ailsun answered 10/7, 2009 at 11:27 Comment(0)
O
4

This code will help you to hide keyboard when you touch outside the edittext or anywhere else. You need to add this code in your activity or you can write in parent activity of your project and it will also hide your keyboard in webview.

@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
    View v = getCurrentFocus();

    if (v != null && (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_MOVE) && v instanceof EditText &&
            !v.getClass().getName().startsWith("android.webkit.")) {
        int[] sourceCoordinates = new int[2];
        v.getLocationOnScreen(sourceCoordinates);
        float x = ev.getRawX() + v.getLeft() - sourceCoordinates[0];
        float y = ev.getRawY() + v.getTop() - sourceCoordinates[1];

        if (x < v.getLeft() || x > v.getRight() || y < v.getTop() || y > v.getBottom()) {
            hideKeyboard(this);
        }

    }
    return super.dispatchTouchEvent(ev);
}

private void hideKeyboard(Activity activity) {
    if (activity != null && activity.getWindow() != null) {
        activity.getWindow().getDecorView();
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
        }
    }
}

public static void hideKeyboard(View view) {
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm != null)
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

Oahu answered 10/7, 2009 at 11:27 Comment(0)
C
4

Hide soft keyboard in Kotlin by creating an extension, which you can use globally. To do this, you need to create a Singleton class.

object Extensions {
    
      fun View.hideKeyboard() {
            val inputMethodManager =                                                 
            context.getSystemService(AppCompatActivity.INPUT_METHOD_SERVICE)           
            as InputMethodManager
            inputMethodManager.hideSoftInputFromWindow(windowToken, 0)
        }
    }

In your activity of fragment class where you need to hide the keyboard, you can call this function with mainlayout id like below

//constraintEditLayout is my main view layout, if you are using other layout like relative or linear layouts you can call with that layout id
constraintEditLayout.hideKeyboard()
Christiachristian answered 10/7, 2009 at 11:27 Comment(0)
P
4

This method works if you need to hide the keyboard in a fragment.

public static void hideSoftKeyboard(Context context, View view) {
    if (context != null && view != null) {
        InputMethodManager imm = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}

For the view, just pass in the

getView() method
Potherb answered 10/7, 2009 at 11:27 Comment(0)
A
4

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)
    editText.requestFocus()
}
Aviary answered 10/7, 2009 at 11:27 Comment(1)
In Kotlin?Equivalency
V
4

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>
Velarium answered 10/7, 2009 at 11:27 Comment(0)
M
4

Here are the best solutions

Solution 1) Set the inputType to “text”

<EditText
android:id="@+id/my_edit_text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Tap here to type"
android:inputType="text" />

This can also be done programmatically via. the method setInputType() (inherited from TextView).

EditText editText = (EditText) findViewById(R.id.my_edit_text);
editText.setRawInputType(InputType.TYPE_CLASS_TEXT | 
InputType.TYPE_TEXT_VARIATION_NORMAL);

Solution 2) Use the InputMethodManager.hideSoftInputFromWindow()

InputMethodManager imm = 
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 0);

or

InputMethodManager imm = (InputMethodManager) 
getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(myEditText.getWindowToken(), 
InputMethodManager.HIDE_NOT_ALWAYS);
M answered 10/7, 2009 at 11:27 Comment(0)
U
4
final RelativeLayout llLogin = (RelativeLayout) findViewById(R.id.rl_main);
        llLogin.setOnTouchListener(
                new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View view, MotionEvent ev) {
                        InputMethodManager imm = (InputMethodManager) this.getSystemService(
                                Context.INPUT_METHOD_SERVICE);
                        imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
                        return false;
                    }
                });
Unship answered 10/7, 2009 at 11:27 Comment(0)
H
4

simple method guys: try this...

private void closeKeyboard(boolean b) {

        View view = this.getCurrentFocus();

        if(b) {
            if (view != null) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
        }
        else {
            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(view, 0);
        }
    }
Huggermugger answered 10/7, 2009 at 11:27 Comment(0)
V
4

simply code : use this code in onCreate()

getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
);
Virilism answered 10/7, 2009 at 11:27 Comment(0)
H
4

Try This one

public void disableSoftKeyboard(final EditText v) {
    if (Build.VERSION.SDK_INT >= 11) {
        v.setRawInputType(InputType.TYPE_CLASS_TEXT);
        v.setTextIsSelectable(true);
    } else {
        v.setRawInputType(InputType.TYPE_NULL);
        v.setFocusable(true);
    }
}
Hesperides answered 10/7, 2009 at 11:27 Comment(0)
M
4
public static void hideSoftKeyboard(Activity activity) {
    InputMethodManager inputMethodManager = (InputMethodManager) activity
            .getSystemService(Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus()
            .getWindowToken(), 0);
}
Macadamia answered 10/7, 2009 at 11:27 Comment(1)
good answer, but activity.getCurrentFocus() can return nullFrederiksen
T
3

To close or hide the Android soft keyboard programmatically, you can use the following methods:

  1. Using InputMethodManager:

     InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
     imm.hideSoftInputFromWindow(yourEditText.getWindowToken(), 0);
    
  2. Using View's onEditorAction:

    If you have an EditText view and want to hide the soft keyboard when the user presses the "Done" or "Enter" key, you can use the onEditorAction listener:

     yourEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
         @Override
         public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
             if (actionId == EditorInfo.IME_ACTION_DONE) {
                 InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                 imm.hideSoftInputFromWindow(yourEditText.getWindowToken(), 0);
                 return true;
             }
             return false;
         } });
    
  3. Programmatically clear focus:

    Another approach is to programmatically clear focus from the EditText view, which will cause the soft keyboard to be hidden:

     yourEditText.clearFocus();
    

    Remember to replace yourEditText with the actual reference to your EditText view. Also, make sure you have the appropriate permissions declared in your Android manifest file, specifically android.permission.INPUT_METHOD.

These methods will allow you to programmatically hide the soft keyboard on an Android device.

Tormoria answered 10/7, 2009 at 11:27 Comment(1)
This is probably the result of plagiarism, most likely ChatGPT (or similar) plagiarism. It is completely out of whack with all other posts by this user.Equivalency
D
3

By adding the generic method to your utility or helper class. By just calling itself, you can hide and show the 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)
    }
    window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN)
}

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)
}
Deirdredeism answered 10/7, 2009 at 11:27 Comment(0)
S
3

I use Kotlin extensions for showing and hiding the keyboard.

fun View.showKeyboard() {
  this.requestFocus()
  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)
}
Steerageway answered 10/7, 2009 at 11:27 Comment(0)
I
3

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);
}
Isoprene answered 10/7, 2009 at 11:27 Comment(0)
L
3

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, this@ActivityName)

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

Lemniscus answered 10/7, 2009 at 11:27 Comment(4)
Is there any difference between Context.INPUT_METHOD_SERVICE and Activity.INPUT_METHOD_SERVICE? Both seem to workStrenuous
Also, you code sample will throw IllegalStateExceptionStrenuous
@Strenuous where you think that it will throw the Exception?Lemniscus
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.Strenuous
G
3

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);
}
Garbage answered 10/7, 2009 at 11:27 Comment(0)
E
3

If your application is targeting API Level 21 or more than there is a default method to use:

editTextObj.setShowSoftInputOnFocus(false);

Make sure you have set below code in EditText XML tag.

<EditText  
    ....
    android:enabled="true"
    android:focusable="true" />
Extrovert answered 10/7, 2009 at 11:27 Comment(0)
M
3

In Android to hide the Vkeyboard by InputMethodManage you can cal hideSoftInputFromWindow by passing in the token of the window containing your focused view.

View view = this.getCurrentFocus();
if (view != null) {  
InputMethodManager im = 
(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
im.hideSoftInputFromWindow(view.getWindowToken(), 0);
}

By Calling editText.clearFocus() and then InputMethodManager.HIDE_IMPLICIT_ONLY even works

Martica answered 10/7, 2009 at 11:27 Comment(0)
S
3

you can simply add this code where you want to hide the soft keyboard"

                        // Check if no view has focus:
                            View view = getCurrentFocus();
                            if (view != null) {
                                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                            }
Squirt answered 10/7, 2009 at 11:27 Comment(0)
R
3

This worked for me.

public static void hideKeyboard(Activity act, EditText et){
    Context c = act.getBaseContext();
    View v = et.findFocus();
    if(v == null)
        return;
    InputMethodManager inputManager = (InputMethodManager) c.getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
Relief answered 10/7, 2009 at 11:27 Comment(0)
B
2

that's Working for me

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    if (imm.isActive())
        imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
Bevatron answered 10/7, 2009 at 11:27 Comment(0)
S
2

This one works for me. You just need to pass the element inside it.

InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(AutocompleteviewDoctorState.getWindowToken(), 0);
Strict answered 10/7, 2009 at 11:27 Comment(0)
A
2

Kotlin

class KeyboardUtils{
    
    companion object{
        fun hideKeyboard(activity: Activity) {
            val imm: InputMethodManager = activity.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
            var view: View? = activity.currentFocus
            if (view == null) {
                view = View(activity)
            }
            imm.hideSoftInputFromWindow(view.windowToken, 0)
        }
    }
}

Then just call it wherever you need

Fragments

KeyboardUtils.hideKeyboard(requireActivity())

Activities

 KeyboardUtils.hideKeyboard(this)
Acromegaly answered 10/7, 2009 at 11:27 Comment(0)
R
2

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

Reseau answered 10/7, 2009 at 11:27 Comment(0)
O
2

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)
        }
    }
Obrien answered 10/7, 2009 at 11:27 Comment(0)
E
2

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;
    }
});
Edi answered 10/7, 2009 at 11:27 Comment(0)
D
2
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 work....@ASK

Disavow answered 10/7, 2009 at 11:27 Comment(0)
P
2

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.

Polash answered 10/7, 2009 at 11:27 Comment(0)
P
2

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()
Palfrey answered 10/7, 2009 at 11:27 Comment(0)
B
2

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

Barncard answered 10/7, 2009 at 11:27 Comment(0)
F
2
/** 
 *
 *   Hide I Said!!!
 *
 */
public static boolean hideSoftKeyboard(@NonNull Activity activity) {
    View currentFocus = activity.getCurrentFocus();
    if (currentFocus == null) {
        currentFocus = activity.getWindow().getDecorView();
        if (currentFocus != null) {
            return getSoftInput(activity).hideSoftInputFromWindow(currentFocus.getWindowToken(), 0, null);
        }
    }
    return false;
}

public static boolean hideSoftKeyboard(@NonNull Context context) {
   if(Activity.class.isAssignableFrom(context.getClass())){
       return hideSoftKeyboard((Activity)context);
   }
   return false;
}

public static InputMethodManager getSoftInput(@NonNull Context context) {
    return (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
}
Falcone answered 10/7, 2009 at 11:27 Comment(0)
H
2

Depite all those answers, just to be simple enough, I have written a common method to do this :

/**
 * hide soft keyboard in a activity
 * @param activity
 */
public static void hideKeyboard (Activity activity){
    activity.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    if (activity.getCurrentFocus() != null) {
        InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
    }
}
Hydrotherapeutics answered 10/7, 2009 at 11:27 Comment(0)
A
2
private void hideSoftKeyboard() {
    View view = getView();
    if (view != null) {
        InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
                .getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
}
Activist answered 10/7, 2009 at 11:27 Comment(0)
I
2

An alternative using SearchView would be to use this code:

searchView = (SearchView) searchItem.getActionView();    
searchView.setOnQueryTextListener(new OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String query) {
        InputMethodManager imm = (InputMethodManager)
        getSystemService(getApplicationContext().INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(searchView.getApplicationWindowToken(), 0);
    }
}

This is a SearchView search box in the ActionBar that when the text from the query is submitted (the user presses either Enter key or a search button/icon), then the InputMethodManager code gets activated and makes your soft keyboard go down. This code was put in my onCreateOptionsMenu(). searchItem is from MenuItem which is part of the default code for the onCreateOptionsmenu(). Thanks to @mckoss for a good chunk of this code!

Improve answered 10/7, 2009 at 11:27 Comment(0)
G
2
public static void closeInput(final View caller) {  
    caller.postDelayed(new Runnable() {
        @Override
        public void run() {
            InputMethodManager imm = (InputMethodManager) caller.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(caller.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }, 100);
}

This method generally works, but there is one condition: you can't have android:windowSoftInputMode="any_of_these" set

Goaltender answered 10/7, 2009 at 11:27 Comment(0)
N
2

This method will always always work at any cost. Just Use it wherever you want to hide the keyboard

public static void hideSoftKeyboard(Context mContext,EditText username){
        if(((Activity) mContext).getCurrentFocus()!=null && ((Activity) mContext).getCurrentFocus() instanceof EditText){
            InputMethodManager imm = (InputMethodManager)mContext.getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(username.getWindowToken(), 0);
        }
    }

Use it like this :

Whatever is the version of Android. This method will surely work

Nevis answered 10/7, 2009 at 11:27 Comment(0)
J
2

Tried all here in desperation, combining all methods, and of course the keyboard will not close in Android 4.0.3 (it did work in Honeicomb AFAIR).

Then suddenly I found an apparently winning combination:

textField.setRawInputType(InputType.TYPE_CLASS_TEXT |InputType.TYPE_TEXT_VARIATION_NORMAL);

combined with your usual recipes

blahblaj.hideSoftInputFromWindow ...

hope this stops somebody from committing suicide .. I was close to it. Of course, I have no idea why it works.

Joyous answered 10/7, 2009 at 11:27 Comment(0)
P
2

I created a layout partially from xml and partially from a custom layout engine, which is all handled in-code. The only thing that worked for me was to keep track of whether or not the keyboard was open, and use the keyboard toggle method as follows:

public class MyActivity extends Activity
{
    /** This maintains true if the keyboard is open. Otherwise, it is false. */
    private boolean isKeyboardOpen = false;

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        LayoutInflater inflater;
        inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentView = inflater.inflate(context.getResources().getIdentifier("main", "layout", getPackageName()), null);

        setContentView(contentView);
        contentView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() 
        {
            public void onGlobalLayout() 
            {
                Rect r = new Rect();
                contentView.getWindowVisibleDisplayFrame(r);
                int heightDiff = contentView.getRootView().getHeight() - (r.bottom - r.top);
                if (heightDiff > 100) 
                    isKeyboardVisible = true;
                else
                    isKeyboardVisible = false;
             });
         }
    }

    public void closeKeyboardIfOpen()
    {
        InputMethodManager imm;
        imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (isKeyboardVisible)
            imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
    }   
}
Palfrey answered 10/7, 2009 at 11:27 Comment(0)
B
1

I tried this. Works well, tested on Nougat API 24.

import android.app.Activity
import androidx.core.view.WindowCompat
import androidx.core.view.WindowInsetsCompat
import androidx.fragment.app.Fragment


fun Activity.hideKeyboard() {
    getInsetController().hide((WindowInsetsCompat.Type.ime()))
}

fun Activity.showKeyboard() {
    getInsetController().show((WindowInsetsCompat.Type.ime()))
}

fun Fragment.hideKeyboard() {
    requireActivity().getInsetController().hide((WindowInsetsCompat.Type.ime()))
}

fun Fragment.showKeyboard() {
    requireActivity().getInsetController().show((WindowInsetsCompat.Type.ime()))
}

fun Activity.getInsetController() = WindowCompat.getInsetsController(window, window.decorView)
Beeswing answered 10/7, 2009 at 11:27 Comment(0)
B
1

Don't forget: In system settings of smartphone is in "Input methods and Languages -> Physical keyboard -> Show OnScreen Keyboard -> On/Off". This settings "interfere" all programming solutions which are here! I had to disable/enable this settings too for complete hide/show onscreen keyboard! Because I am developing for device MC2200 I did it with "EMDK Profile manage -> Ui manager -> Virtual Keyboard state -> Show/Hide"

Blown answered 10/7, 2009 at 11:27 Comment(0)
L
1

Here is the easiest way to hide the soft keyboard with Kotlin:

//hides soft keyboard anything else is tapped( screen, menu bar, buttons, etc. )
override fun dispatchTouchEvent( ev: MotionEvent? ): Boolean {
    if ( currentFocus != null ) {
        val imm = getSystemService( Context.INPUT_METHOD_SERVICE ) as InputMethodManager
        imm.hideSoftInputFromWindow( currentFocus!!.windowToken, 0 )
    }
    return super.dispatchTouchEvent( ev )
}
Losse answered 10/7, 2009 at 11:27 Comment(0)
C
1

If you set in your .xml android:focused="true", then it would not work, because it is a set like it is not changeable.

So the solution:

android:focusedByDefault="true"

Then it will set it once and can hide or show the keyboard.

Cotillion answered 10/7, 2009 at 11:27 Comment(0)
K
1
 //In Activity
        View v = this.getCurrentFocus();
        if (v != null) {
            InputMethodManager im = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }


//In Fragment
        View v = getActivity().getCurrentFocus();
        if (v != null) {
            InputMethodManager im = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
```
Kathlenekathlin answered 10/7, 2009 at 11:27 Comment(0)
A
1

There is a new API in Android 11 called WindowInsetsController. Apps can get access to a controller from any view, by which we can use the hide() and show() methods:

val controller = view.windowInsetsController

// Show the keyboard (IME)
controller.show(Type.ime())

// Hide the keyboard
controller.hide(Type.ime())

See WindowInsetsController

Anabas answered 10/7, 2009 at 11:27 Comment(0)
B
1

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

 fun hideKeyboard(activity: Activity?) {
    val inputManager: InputMethodManager? = 
    activity?.getSystemService(Context.INPUT_METHOD_SERVICE) as? 
    InputMethodManager
    // Check if no view has focus:
    val v = activity?.currentFocus ?: return
    inputManager?.hideSoftInputFromWindow(v.windowToken, 0)
 }
Bolometer answered 10/7, 2009 at 11:27 Comment(0)
N
1

This 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)
}
Nadaba answered 10/7, 2009 at 11:27 Comment(1)
What is that? Kotlin?Equivalency
A
1

Try this:

Force fully the Android soft input keyboard:

Create a method in a helper class

InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null)
    imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
Avirulent answered 10/7, 2009 at 11:27 Comment(0)
S
1

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

Saddlebacked answered 10/7, 2009 at 11:27 Comment(0)
S
1

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">
Straiten answered 10/7, 2009 at 11:27 Comment(0)
F
1
 fun hideKeyboard(appCompatActivity: AppCompatActivity) {
        val view = appCompatActivity.currentFocus
        val imm = appCompatActivity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }
Flagwaving answered 10/7, 2009 at 11:27 Comment(0)
F
1

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);
}
Fukien answered 10/7, 2009 at 11:27 Comment(0)
M
1

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);
Maier answered 10/7, 2009 at 11:27 Comment(0)
S
1

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)
    }
}
Stultz answered 10/7, 2009 at 11:27 Comment(0)
S
1

Some kotlin code:

Hide keyboard from Activity:

(currentFocus ?: View(this))
            .apply { (getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager)
                        .hideSoftInputFromWindow(windowToken, 0) }
Sappington answered 10/7, 2009 at 11:27 Comment(0)
O
1

Kotlin version

val imm: InputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
//Hide:
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
//Show
imm.toggleSoftInput(InputMethodManager.SHOW_IMPLICIT, 0);
Orthographize answered 10/7, 2009 at 11:27 Comment(1)
Creating an extension function on Activity seems like a decent approach fun Activity.closeKeyboard() { (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).apply { hideSoftInputFromWindow(window.decorView.windowToken, 0) } }Sporocarp
O
1

After reading all the answers above and in another post, I still didn't succeed in getting the keyboard to open automatically.

In my project I created a dialog (AlertDialog) dynamically (by programming it without or with minimum of needed XML).

So I was doing something like:

    dialogBuilder = new AlertDialog.Builder(activity);

    if(dialogBuilder==null)
        return false; //error

    inflater      = activity.getLayoutInflater();
    dialogView    = inflater.inflate(layout, null);
    ...

And after finishing setting-up all the views (TextView, ImageView, EditText,etc..) I did:

        alertDialog = dialogBuilder.create();

        alertDialog.show();

After playing around with all the answers I found out that most of them work IF you know WHERE to put the request... And that was the key to all.

So, the trick is to put it BEFORE the creation of the dialog: alertDialog.show() in my case, this worked like charm:

        alertDialog = dialogBuilder.create();           
        alertDialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

        //And only when everything is finished - let's bring up the window - 
        alertDialog.show();

        //Viola... keyboard is waiting for you open and ready...
        //Just don't forget to request focus for the needed view (i.e. EditText..)

I'm quite sure this principle is the same with all windows, so pay attention to the location of your "showKeyboard" code - it should be before the window is launched.

A small request from the Android SDK dev team:

I think that all this is unnecessary as you can see thousands of programmers from all over the world are dealing with this ridiculous and trivial problem, while its solution should be clean and simple: IMHO if I get requestFocus() to an input-oriented view (such as EditText), the keyboard should open automatically, unless the user asks not-to, so, I think the requestFocus() method is the key here and should accept boolean showSoftKeyboard with default value of true: View.requestFocus(boolean showSoftKeyboard);

Hope this will help others like me.

Oilstone answered 10/7, 2009 at 11:27 Comment(0)
A
1

You only need to write one line inside your manifest activity tag

 android:windowSoftInputMode="stateAlwaysHidden|adjustPan"

and it will work.

Atalayah answered 10/7, 2009 at 11:27 Comment(0)
I
1

surround it with try catch, so that is keyboard is already closed, app would not crash :

try{

View view = this.getCurrentFocus();
if (view != null) {  
    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}catch (Exception e)
{
  e.printStackTrace();
}
Isopropanol answered 10/7, 2009 at 11:27 Comment(0)
P
0

There are various methods to do that, some of them are-

1.) Using Toggle soft input

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

2.) Using view

InputMethodManager imm = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);

3.) Using clearFocus()

editText.clearFocus();

Overall your code will look like this,

public class YourActivity extends AppCompatActivity {

    private EditText editText;
    private Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.your_layout);

        editText = findViewById(R.id.editText);
        button = findViewById(R.id.button);
 
        View rootLayout = findViewById(R.id.rootLayout); // Replace with the ID of your root layout
        rootLayout.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    hideKeyboard();
                }
                return false;
            }
        });
 
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) { 
            }
        });
    }

    private void hideKeyboard() {
        View view = this.getCurrentFocus();
        if (view != null) {
            InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }
}
Profiterole answered 10/7, 2009 at 11:27 Comment(0)
S
0

You can simply add OnFocusChangeListener to the your view. For example, editText in this case.

editText.onFocusChangeListener = View.OnFocusChangeListener { _, hasFocus ->
        if (!hasFocus) {
           val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
           val focusedView = currentFocus
           if (imm != null && focusedView != null) {
              imm.hideSoftInputFromWindow(focusedView.windowToken, 0)
           }
        }
    }
Snowberry answered 10/7, 2009 at 11:27 Comment(0)
D
0

You can use the extensions below to hide and show the soft keyboard:

fun Fragment.showKeyboard(view: View) {
    view.isFocusableInTouchMode = true
    view.requestFocus()
    val imm = view.context?.getSystemService(Context.INPUT_METHOD_SERVICE)
        as InputMethodManager
    imm.showSoftInput(view, InputMethodManager.SHOW_IMPLICIT) }

fun Fragment.hideKeyboard(view: View) {
    view.clearFocus()
    val imm = view.context?.getSystemService(Context.INPUT_METHOD_SERVICE)
       as InputMethodManager
    imm.hideSoftInputFromWindow(view.windowToken, 0) }

To call the extension, you can simply follow the below in your fragments:

showKeyboard(Your edittext ID)

hideKeboard(Your edittext ID)
Demonstrator answered 10/7, 2009 at 11:27 Comment(0)
C
0

Kotlin Version:

fun showKeyboard(mEtSearch: EditText, context: Context) {
        mEtSearch.requestFocus()
        val imm: InputMethodManager =
            context.getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.showSoftInput(mEtSearch, 0)
}
Clarino answered 10/7, 2009 at 11:27 Comment(0)
B
0

My solution:

Construct it with an activity (a view is optional), use a handler to post this (with some delay, for example, 100 ms is better). Directly calling the input manager will not work sometimes. It only works while we can get the Activity. I think it is normal.

If you can get your root viewgroup or editview when you call. Just send it in for a better result.

public class CloseSoftKeyboardRunnable implements Runnable
{
    Activity activity;
    View view;  // For dialog will occur context getcurrentfocus == null. send a rootview to find currentfocus.

    public CloseSoftKeyboardRunnable(Activity activity, View view)
    {
        this.activity = activity;
        this.view = view;
    }

    public CloseSoftKeyboardRunnable(Activity activity)
    {
        this.activity = activity;
    }
    @Override
    public void run() {
        if (!activity.isFinishing())
        {
            InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);

            if (view == null) {
                view = activity.getCurrentFocus();
            }
            else
            {
                try {
                    view = ((ViewGroup)view).getFocusedChild();
                }
                catch ( Exception e) {}
            }

            Window window =  activity.getWindow();

            if (window != null)
            {
                if (view == null) {
                    try {
                        view = window.getDecorView();
                        view = ((ViewGroup)view).getFocusedChild();
                    }
                    catch ( Exception e) {}
                }

                if (view == null) {
                    view = window.getDecorView();
                }

                if (view != null) {
                    if (view instanceof EditText)
                    {
                        EditText edittext = ((EditText) view);
                        edittext.setText(edittext.getText().toString()); // Reset edit text bug on some keyboards bug
                        edittext.clearFocus();
                    }

                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
                window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
            }
        }
    }
}
Boorish answered 10/7, 2009 at 11:27 Comment(0)
P
0
public final class UtilsKeyboard {
/**
 * Sets the cursor at the end of this edit text and shows a keyboard
 */
public static void focusKeyboard(@NonNull EditText editText) {
    editText.requestFocus();
    editText.setSelection(editText.getText().length());
    showKeyboard(editText);
}

private static void showKeyboard(@NonNull View view) {
    final InputMethodManager manager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    if (manager != null) {
        manager.showSoftInput(view, InputMethodManager.SHOW_FORCED);
    }
}

public static boolean hideKeyboard(@NonNull Window window) {
    View view = window.getCurrentFocus();
    return hideKeyboard(window, view);
}

private static boolean hideKeyboard(@NonNull Window window, @Nullable View view) {
    if (view == null) {
        return false;
    }
    InputMethodManager inputMethodManager = (InputMethodManager) window.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    if (inputMethodManager != null) {
        return inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
    return false;
}

public static boolean hideKeyboard(@Nullable View view) {
    if (view == null) {
        return false;
    }
    InputMethodManager inputMethodManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
    if (inputMethodManager != null) {
        return inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
    return false;
}

/**
 * This will hide the keyboard and unfocus any focused view.
 */
public static void unfocusKeyboard(@NonNull Window window) {
    // When showing the bottom menu, make sure the keyboard isn't and that no view has focus
    hideKeyboard(window);
    final View focused = window.getCurrentFocus();
    if (focused != null) focused.clearFocus();
}}
Padget answered 10/7, 2009 at 11:27 Comment(0)
W
0

There are a lot of answers. If after all nothing works then, here is a tip :),

You can make an EditText and,

edittext.setAlpha(0f);

this edittext will not be seen because of the alpha method. Now use the Above answers on how to show/hide soft keyboard with EditText.

Winebaum answered 10/7, 2009 at 11:27 Comment(0)
R
0
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);
}
Ruscher answered 10/7, 2009 at 11:27 Comment(0)
C
0

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);
}
Cassaba answered 10/7, 2009 at 11:27 Comment(0)
I
0

I have tried all of solutions very much but no solution work for me, so I found my solution: You should have boolean variables like:

public static isKeyboardShowing = false;
InputMethodManager inputMethodManager = (InputMethodManager) getActivity()
            .getSystemService(Context.INPUT_METHOD_SERVICE);

And in a touch screen event you call:

@Override
public boolean onTouchEvent(MotionEvent event) {
    if(keyboardShowing==true){
        inputMethodManager.toggleSoftInput(InputMethodManager.RESULT_UNCHANGED_HIDDEN, 0);
        keyboardShowing = false;
    }
    return super.onTouchEvent(event);
}

And in EditText is in anywhere:

yourEditText.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            yourClass.keyboardShowing = true;

        }
    });
Impulsion answered 10/7, 2009 at 11:27 Comment(0)
H
-1

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

android:imeOptions="actionDone"
Hamburger answered 10/7, 2009 at 11:27 Comment(0)
P
-6

This works for me :

 @Override
 public boolean dispatchTouchEvent(MotionEvent event) {
View v = getCurrentFocus();
boolean ret = super.dispatchTouchEvent(event);

if (v instanceof EditText) {
    View w = getCurrentFocus();
    int scrcoords[] = new int[2];
    w.getLocationOnScreen(scrcoords);
    float x = event.getRawX() + w.getLeft() - scrcoords[0];
    float y = event.getRawY() + w.getTop() - scrcoords[1];

    Log.d("Activity",
            "Touch event " + event.getRawX() + "," + event.getRawY()
                    + " " + x + "," + y + " rect " + w.getLeft() + ","
                    + w.getTop() + "," + w.getRight() + ","
                    + w.getBottom() + " coords " + scrcoords[0] + ","
                    + scrcoords[1]);
    if (event.getAction() == MotionEvent.ACTION_UP
            && (x < w.getLeft() || x >= w.getRight() || y < w.getTop() || y > w
                    .getBottom())) {

        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getWindow().getCurrentFocus()
                .getWindowToken(), 0);
    }
}
return ret;
}
Provitamin answered 10/7, 2009 at 11:27 Comment(0)
P
-10

Just add this property in your EditTect view to hide the keyboard.

android:focusable="false"
Prolong answered 10/7, 2009 at 11:27 Comment(1)
You're just throwing darts, and this one not only missed the board, but almost hit the bartender.Bestiary

© 2022 - 2024 — McMap. All rights reserved.