点击 软键盘 和 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)
}
}