且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用 Kotlin 关闭/隐藏 Android 软键盘

更新时间:2022-12-19 16:43:03

在您的活动、片段中使用以下实用程序函数来隐藏软键盘.

Use the following utility functions within your Activities, Fragments to hide the soft keyboard.

(*)Kotlin 最新版本更新

fun Fragment.hideKeyboard() {
    view?.let { activity?.hideKeyboard(it) }
}

fun Activity.hideKeyboard() {
    hideKeyboard(currentFocus ?: View(this))
}

fun Context.hideKeyboard(view: View) {
    val inputMethodManager = getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
    inputMethodManager.hideSoftInputFromWindow(view.windowToken, 0)
}

无论您在对话框片段和/或活动等中的代码如何,这都会关闭键盘.

This will close the keyboard regardless of your code either in dialog fragment and/or activity etc.

在 Activity/Fragment 中的使用:

hideKeyboard()