我正在尝试用 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/