Android
[안드로이드] EditText 외부 선택 시 키보드 제거_kotlin (Button 터치 예외처리추가)
dada123
2024. 11. 25. 09:39
안드로이드 EditText외에 다른 영역을 선택 했을 때 키보드를 제거 하는 코드이다.
TouchedView ! is Button 조건을 사용하지 않고 dispatchTouch event만 사용했을 경우 키보드가 뜬 상태로 버튼 선택이 되지 않는 SideEffet가 발생하여 선택한 영역이 버튼일 경우에는 제외하는 조건을 추가 하였다.
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()
// 터치된 뷰가 버튼인지 확인
val touchedView = findViewAtPosition(x, y)
if (!rect.contains(x, y) && touchedView !is Button) {
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(focusView.windowToken, 0)
focusView.clearFocus()
}
}
return super.dispatchTouchEvent(ev)
}
private fun findViewAtPosition(x: Int, y: Int): View? {
return window.decorView.findViewById<ViewGroup>(android.R.id.content)?.let { rootView ->
findViewAtPosition(rootView, x, y)
}
}
private fun findViewAtPosition(parent: ViewGroup, x: Int, y: Int): View? {
for (i in 0 until parent.childCount) {
val child = parent.getChildAt(i)
if (child is ViewGroup) {
val foundView = findViewAtPosition(child, x, y)
if (foundView != null) {
return foundView
}
} else {
val rect = Rect()
child.getGlobalVisibleRect(rect)
if (rect.contains(x, y)) {
return child
}
}
}
return null
}