<
点击 软键盘 和 edittext 之外区域 隐藏软键盘
>
上一篇

如何选择 kotlin 的 apply also let with run 标准函数
下一篇

解决win10任务栏图标空白

点击 软键盘 和 EditText 之外区域 隐藏软键盘

利用 Activity 事件分发 判断按压位置是否在 EditText 上 不在则调用关闭逻辑

Activity:


    override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
        if (ev?.action == MotionEvent.ACTION_DOWN) {
            val view = currentFocus
            if (!isInputArea(view, ev)) {
                hideSoftKeyboard()
                view?.clearFocus()
            }
        }
        return super.dispatchTouchEvent(ev)
    }

    private fun isInputArea(view: View?, event: MotionEvent): Boolean {
        if (view != null && view is EditText) {
            val area = intArrayOf(0, 0)
            view.getLocationInWindow(area)
            val left = area[0]
            val top = area[1]
            val bottom = top + view.getHeight()
            val right = left + view.getWidth()
            return event.x > left && event.x < right && event.y > top && event.y < bottom
        }
        return false
    }

    private fun hideSoftKeyboard() {
        val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        val view = currentFocus
        if (view != null) {
            imm.hideSoftInputFromWindow(view.windowToken, 0)
        }
    }

Top
Foot