Android dismiss keyboard

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

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

9条回答
  •  执念已碎
    2021-01-30 00:35

    Here's a Kotlin solution (mixing the various answers in thread)

    Create an extension function (perhaps in a common ViewHelpers class)

    fun Activity.dismissKeyboard() {
        val inputMethodManager = getSystemService( Context.INPUT_METHOD_SERVICE ) as InputMethodManager
        if( inputMethodManager.isAcceptingText )
            inputMethodManager.hideSoftInputFromWindow( this.currentFocus.windowToken, /*flags:*/ 0)
    }
    

    Then simply consume using:

    // from activity
    this.dismissKeyboard()
    
    // from fragment
    activity.dismissKeyboard()
    

提交回复
热议问题