在Kotlin中关闭/隐藏软键盘

4
我有一个按钮和编辑框。当用户在编辑框中完成输入并按下按钮时,我希望关闭软键盘。
或者有任何指南或参考链接可供参考。
4个回答

4

调用此函数隐藏系统键盘:

fun View.hideKeyboard() {
    val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(windowToken, 0)
}

4

我稍微修改了@Serj Ardovic的回复。

private fun hideKeyboard(view: View) {
    view?.apply {
        val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }
}

因为它确实符合我的需求


1
你可以扩展所有的EditText,增加新功能,当EditText失去焦点时,软键盘将被隐藏。如果想要在某些EditText失去焦点时隐藏键盘,只需为该EditText使用以下代码:
editText.hideSoftKeyboardOnFocusLostEnabled(true)

在扩展EditText时,我们只需添加或删除自己的OnFocusLostListener
fun EditText.hideSoftKeyboardOnFocusLostEnabled(enabled: Boolean) {
    val listener = if (enabled)
        OnFocusLostListener()
    else
        null
    onFocusChangeListener = listener
}

这是一个实现了OnFocusLostListener的示例,它会在附加的View失去焦点时隐藏键盘。
class OnFocusLostListener: View.OnFocusChangeListener {
    override fun onFocusChange(v: View, hasFocus: Boolean) {
        if (!hasFocus) {
            val imm = v.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(v.windowToken, 0)
        }
    }
}

0
fun hideSoftKeyboard(mActivity: Activity) {
        // Check if no view has focus:
        val view = mActivity.currentFocus
        if (view != null) {
            val inputManager = mActivity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
            inputManager.hideSoftInputFromWindow(view.windowToken, 0)
        }
    }

    fun showKeyboard(yourEditText: EditText, activity: Activity) {
        try {
            val input = activity
                    .getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager
            input.showSoftInput(yourEditText, InputMethodManager.SHOW_IMPLICIT)
        } catch (e: Exception) {
            e.printStackTrace()

        }
    }

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