仅在单击时隐藏键盘,如果用户滚动则保留它

Hide keyboard only on click, keep it if user is scrolling

我试图在用户点击屏幕时隐藏键盘。然而,例如,如果有一个带有 ScrollView 的布局(比方说一个带有多个 EditText 的表单),则应用程序不得在用户 滚动时关闭键盘。 知道吗?

    override fun dispatchTouchEvent(event: MotionEvent): Boolean {
        if(event.action == MotionEvent.ACTION_UP){
            val focusedView = currentFocus
            if (focusedView is EditText) {
                val areaOutsideFocusedView = Rect()
                focusedView.getGlobalVisibleRect(areaOutsideFocusedView)
                if (!areaOutsideFocusedView.contains(event.rawX.toInt(), event.rawY.toInt())) {
                    hideKeyboard()
                    val rootViewGroup = focusedView.rootView as ViewGroup
                    val descendantFocusability = rootViewGroup.descendantFocusability
                    rootViewGroup.descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS
                    focusedView.clearFocus()
                    rootViewGroup.descendantFocusability = descendantFocusability
                }
            }
        }
        return super.dispatchTouchEvent(event)
    }

我通过添加一个存储最后一个事件操作的变量解决了这个问题。

var lastEventAction : Int = -1

override fun dispatchTouchEvent(event: MotionEvent): Boolean {
        if(lastEventAction != MotionEvent.ACTION_MOVE && event.action == MotionEvent.ACTION_UP){
            val focusedView = currentFocus
            if (focusedView is EditText) {
                val areaOutsideFocusedView = Rect()
                focusedView.getGlobalVisibleRect(areaOutsideFocusedView)
                if (!areaOutsideFocusedView.contains(event.rawX.toInt(), event.rawY.toInt())) {
                    hideKeyboard()
                    val rootViewGroup = focusedView.rootView as ViewGroup
                    val descendantFocusability = rootViewGroup.descendantFocusability
                    rootViewGroup.descendantFocusability = ViewGroup.FOCUS_BLOCK_DESCENDANTS
                    focusedView.clearFocus()
                    rootViewGroup.descendantFocusability = descendantFocusability
                }
            }
        }
        lastEventAction = event.action
        return super.dispatchTouchEvent(event)
    }