DEV Community

Rohit Jakhar
Rohit Jakhar

Posted on

Hide Keyboard in Android using Kotlin in 20 second

Write these extension function in utility class to hide the soft keyboard

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)
}
Enter fullscreen mode Exit fullscreen mode

Now use this method in your activity and fragment where you want hide keyboard.

hideKeyboard
Enter fullscreen mode Exit fullscreen mode

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

Top comments (0)