Close/hide the Android Soft Keyboard with Kotlin

Use the following utility functions within your Activities, Fragments to hide the soft keyboard.

(*)Update for the latest Kotlin version

fun Fragment.hideKeyboard() {
    view?.let { activity?.hideKeyboard(it) }
}

fun Activity.hideKeyboard() {
    hideKeyboard(currentFocus ?: View(this))
}

fun Context.hideKeyboard(view: View) {
    val inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}

This will close the keyboard regardless of your code either in dialog fragment and/or activity etc.

Usage in Activity/Fragment:

hideKeyboard()

Leave a Comment