4360

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. Can someone provide a simple example of how to achieve this?

8
  • 19
    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? Commented Jun 1, 2011 at 15:48
  • 19
    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=0x00000000
    – rupps
    Commented May 15, 2013 at 13:28
  • 5
    /** * 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); } Commented Jan 13, 2014 at 13:30
  • this worked for me
    – nmxprime
    Commented Jun 20, 2014 at 12:45
  • Need to play with InputMethodManager with the INPUT_METHOD_SERVICE to handle soft keyboard like readyandroid.wordpress.com/show-hide-android-soft-keyboard Commented May 4, 2018 at 6:09

131 Answers 131

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);
    }
}
0
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;
    }
});
1
  • Try this as well - this worked for me: InputMethodManager imm = ((InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE)); imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
    – zmicer
    Commented Nov 7, 2013 at 12:20
12

use this

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

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);
}
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);
3
  • 1
    Very clever. If the user wants another search, just click search again.
    – Alex
    Commented Mar 23, 2013 at 14:48
  • 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).
    – Azurespot
    Commented Jul 6, 2014 at 23:46
  • @Noni A, stackoverflow.com/questions/7409288/… Commented Apr 18, 2016 at 21:50
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);
        }
    }
}
9

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) {
    }
}
0
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).

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. Commented Sep 27, 2012 at 8:26
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.

1
  • 1
    in my case, in addition to android:imeOptions="actionDone" also needed to include android:singleLine="true"
    – tmr
    Commented Oct 25, 2014 at 6:37
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
}
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)
    }
}
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).

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

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

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"  />
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.)
    – Rock Lee
    Commented May 24, 2016 at 21:11
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);

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
    }
}
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
0
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()
2
  • instead of writing the same logic again just call activity?.hideKeyboard from your fragment implementation Commented Jul 15, 2020 at 13:33
  • 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?.windowToken Commented Jul 15, 2020 at 13:41
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"
0
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)
    }
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();
    }
}
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);
}
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);
    }
}
5

For those looking for jetpack compose answer.

val keyboardController = LocalSoftwareKeyboardController.current

//for showing the keyboard
keyboardController?.show()
//for hiding the keyboard
keyboardController?.hide()
5

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

<activity
    android:name=".MainActivity"
    android:screenOrientation="portrait"
    android:windowSoftInputMode="adjustPan"/>
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.

4
public static void hideSoftKeyboard(Activity activity) {
    InputMethodManager inputMethodManager = (InputMethodManager) activity
            .getSystemService(Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(activity.getCurrentFocus()
            .getWindowToken(), 0);
}
1
  • 1
    good answer, but activity.getCurrentFocus() can return null Commented Aug 27, 2014 at 15:59
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);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.