Android dismiss keyboard

Viewed 73050

How do I dismiss the keyboard when a button is pressed?

10 Answers

This Solution make sure that it hides keyboard also do nothing if it not opened. It uses extension so it can be used from any Context Owner class.


fun Context.dismissKeyboard() {
    val imm by lazy { this.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager }
    val windowHeightMethod = InputMethodManager::class.java.getMethod("getInputMethodWindowVisibleHeight")
    val height = windowHeightMethod.invoke(imm) as Int
    if (height > 0) {
        imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0)
    }
}


By using the context of the view, we can achieve the desired outcome with the following extension methods in Kotlin:

/**
 * Get the [InputMethodManager] using some [Context].
 */
fun Context.getInputMethodManager(): InputMethodManager {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        return getSystemService(InputMethodManager::class.java)
    }

    return getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
}

/**
 * Dismiss soft input (keyboard) from the window using a [View] context.
 */
fun View.dismissKeyboard() = context
        .getInputMethodManager()
        .hideSoftInputFromWindow(
                windowToken
                , 0
        )

Once these are in place, just call:

editTextFoo.dismiss()

Kotlin:

To dismiss the keyboard, call clearFocus() on the respective element when the button is clicked.

Example:

mSearchView.clearFocus()
Related