How do I dismiss the keyboard when a button is pressed?
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()