Android dismiss keyboard

后端 未结 9 509
面向向阳花
面向向阳花 2021-01-29 23:51

How do I dismiss the keyboard when a button is pressed?

9条回答
  •  时光取名叫无心
    2021-01-30 00:24

    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)
        }
    }
    
    
    

提交回复
热议问题