/**
* 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
)
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)
}
}
private void hideSoftKeyBoard() {
InputMethodManager imm = (InputMethodManager) getContext().getSystemService(INPUT_METHOD_SERVICE);
if (imm.isAcceptingText()) { // verify if the soft keyboard is open
imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
}
}