I am using a workaround to detect if a click was outside of an EditText to performs some logic. When user clicks on the EditText the keyboard appears. The windowSoftInputMode
is set to adjustPan
. So the issue is that I am seeing the view bounds are not recalculated after the content is pushed up on the page. It is still returning the previous bounds with the closed keyboard.
So here is the code I am using
override fun dispatchTouchEvent(ev: MotionEvent?): Boolean {
currentFocus?.let {
tryCloseKeyboardAndClearFocusFromEditText(currentFocus as View, ev)
}
return super.dispatchTouchEvent(ev)
}
private fun tryCloseKeyboardAndClearFocusFromEditText(focus: View, ev: MotionEvent?) {
if (focus is TextInputEditText) {
val outRect = Rect()
(focus as? TextInputEditText)?.getGlobalVisibleRect(outRect)
if (!outRect.contains(ev?.rawX?.toInt() ?: 0, ev?.rawY?.toInt() ?: 0)) {
closeKeyboard()
(focus as? TextInputEditText)?.clearFocus()
}
}
}
So getGlobalVisibleRec
always returns the same values not matter if the keyboard is open or closed and the content on the screen was actually pushed up. The MotionEvent coordinates are 100, 400 for example and EditText is showing 60, 490 for example event though I am clicking directly on it.
Is there a way to get actual view rect on the screen with regards of the offset when keyboard is closed or open?
Found a solution, so I am using the getLocationInWindow
now and adding height
and width
to figure out the bounds. Works as expected. If someone can explain why getGlobalVisibleRect
and getLocalVisibleRect
didn't work please do.
private fun tryCloseKeyboardAndClearFocusFromEditText(focus: View, ev: MotionEvent?) {
if (focus is TextInputEditText) {
val location = IntArray(2)
(focus as? TextInputEditText)?.let{
it.getLocationInWindow(location)
val outRect = Rect(location[0], location[1], location[0] + it.width, location[1] + it.height)
if (!outRect.contains(ev?.rawX?.toInt() ?: 0, ev?.rawY?.toInt() ?: 0)) {
closeKeyboard()
it.clearFocus()
}
}
}
}