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

我正在尝试用 Kotlin 编写一个简单的 Android 应用程序。我的布局中有一个 EditText 和一个 Button。在编辑字段中写入并单击按钮后,我想隐藏虚拟键盘。

有一个热门问题 Close/hide the Android Soft Keyboard关于用 Java 做,但据我了解,应该有 Kotlin 的替代版本。我该怎么做?

最佳答案

在您的 Activity 、 fragment 中使用以下实用功能来隐藏软键盘。

(*)更新为最新的 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)
}

无论您在对话框 fragment 和/或 Activity 等中的代码如何,这都会关闭键盘。

在 Activity/Fragment 中的使用:

hideKeyboard()

https://stackoverflow.com/questions/41790357/

相关文章:

android - 使用 Retrofit 方法更具表现力

kotlin - 如何在一行上声明多个属性

kotlin - 在 Kotlin 中复制 map 最聪明的方法是什么?

android - 如何在 Kotlin 中获取当前的本地日期和时间

android - 使用 Kotlin 组合整数标志的最佳方法?

kotlin - 传递 null 时,有没有办法在非可选参数上使用默认值?

kotlin - 如何在 Kotlin 中定义非序数枚举?

android - 从 Activity Kotlin 中获取额外的字符串

android - 在 Kotlin 中的原始类型属性上不允许使用 lateinit 修饰符

kotlin - 为什么这个 Kotlin 方法有封闭的反引号?