Android dismiss keyboard

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

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

9条回答
  •  滥情空心
    2021-01-30 00:20

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

提交回复
热议问题