如何使用Kotlin从片段关闭软键盘?

10
我希望能够在片段内部关闭软键盘,我找到了很多答案,但它们都是用Java编写的。通常情况下,我可以很容易地将其转换为Kotlin,但是这个问题让我很难受。
我最接近的解决方法是这个:
fun closeKeyboard() {
    val activity = activity as FeedActivity

    val view = activity.currentFocus
    if (view != null) {
        val imm = ContextCompat.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
        imm!!.hideSoftInputFromWindow(view!!.getWindowToken(), 0)
    }
}

但是我在处理这一部分时遇到了麻烦 getSystemService(Context.INPUT_METHOD_SERVICE)

3个回答

18

除了ContextCompat.getSystemService之外,一切都是正确的。使用Activity实例替代ContextCompat

val imm = activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(view!!.getWindowToken(), 0)

2
那个视图!! 很可能会导致你的应用程序崩溃。 - M'aiq the Coder
@M'aiqtheCoder 添加 if (view != null) 来防止崩溃。 - Andrew Churilo

4
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)
}

创建一个简单的扩展函数,可以从任何地方调用它并获取上下文


1

我来到这里寻找类似问题的答案,但在没有直接访问Activity实例的情况下。

尽管已经有一个被接受的答案,但是如果您传递所请求服务的类,仍然可以使用ContextCompat,并获得转换的好处,像这样:

val imm = ContextCompat.getSystemService(view.context, InputMethodManager::class.java)
imm?.hideSoftInputFromWindow(view.windowToken, 0)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接