본문 바로가기

Android - Snippet

키패드 외부 영역 Touch시 clearFocus


override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
    val focusView = currentFocus
    if (focusView != null) {
        val rect = Rect()
        focusView.getGlobalVisibleRect(rect)
        val x = ev!!.x.toInt()
        val y = ev!!.y.toInt()
        if (!rect.contains(x, y)) {
            val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
            imm.hideSoftInputFromWindow(focusView.windowToken, 0)
            focusView.clearFocus()
        }
    }
    return super.dispatchTouchEvent(ev)
}