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