使用 Kotlin 关闭/隐藏 Android 软键盘 [英] Close/hide the Android Soft Keyboard with Kotlin
问题描述
我正在尝试用 Kotlin 编写一个简单的 Android 应用程序.我的布局中有一个 EditText 和一个 Button.在编辑字段中写入并单击按钮后,我想隐藏虚拟键盘.
I'm trying to write a simple Android app in Kotlin. I have an EditText and a Button in my layout. After writing in the edit field and clicking on the Button, I want to hide the virtual keyboard.
有一个热门问题 关闭/隐藏 AndroidSoft Keyboard 关于用 Java 来做,但据我所知,Kotlin 应该有一个替代版本.我该怎么做?
There is a popular question Close/hide the Android Soft Keyboard about doing it in Java, but as far as I understand, there should be an alternative version for Kotlin. How should I do it?
推荐答案
在您的活动、片段中使用以下实用程序函数来隐藏软键盘.
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()
这篇关于使用 Kotlin 关闭/隐藏 Android 软键盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!