我想隐藏键盘

I want to hide the keyboard

我想隐藏键盘,但我想把它写在 class 中。将它用于所有活动。我需要编辑文本删除焦点代码

class Extensions(){
fun hideSoftKeyboard(view: View) {
    val imm =getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(view.windowToken, 0)
}

}

问题描述

没有为参数传递值 'serviceClass'

类型不匹配:推断的类型是字符串,但上下文是预期的

新代码:但是我无法执行外部点击事件

fun Activity.hideKeyboard() {
    val view = currentFocus
    if (view != null) {
        view.clearFocus()
        val inputMethodManager =
            getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager

        inputMethodManager.hideSoftInputFromWindow(
            view.windowToken,
            InputMethodManager.HIDE_NOT_ALWAYS
        )
    }
}

如果您使用的是 Jetpack Compose;

@Composable
fun MainScreenView(){

    val keyboardController = LocalSoftwareKeyboardController.current
    keyboardController.hide()

您可以在编辑文本上创建一个扩展功能,它会为您执行此操作

fun EditText.hideKeyboard() {
    clearFocus()
    val imm = context.getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
    imm.hideSoftInputFromWindow(getWindowToken(), 0)
}

我还没有测试过,请测试一下,告诉我它是否有效。

Extensions.kt

fun Activity.hideKeyboard(event: MotionEvent) {
    if (event.action == MotionEvent.ACTION_DOWN){
        val view = currentFocus
        if (view != null) {
            view.clearFocus()
            val outRect = Rect()
            view.getGlobalVisibleRect(outRect)
            if (!outRect.contains(event.rawX.toInt(), event.rawY.toInt())) {
                val inputMethodManager =
                    getSystemService(Activity.INPUT_METHOD_SERVICE) as InputMethodManager

                inputMethodManager.hideSoftInputFromWindow(
                    view.windowToken,
                    InputMethodManager.HIDE_NOT_ALWAYS
                )
            }
        }
    }
}

YouActivity

override fun dispatchTouchEvent(event: MotionEvent): Boolean {
        hideKeyboard(event)
        return super.dispatchTouchEvent(event)
    }