I want to use dispatchTouchEvent
in one of many Fragments
created in Activity
. Problem is that dispatchTouchEvent
causing some issues with focusing in other fragments, so I want to have it active only in single fragment, but Fragment
doesnt have this type of function.
Is there any way how to implement it in Fragment?
I need this function, because I had issues with EditTexts
and they refused to loose focus if I made onClickListener
for my fragment root view (keyboard was still visible and EditTexts
were still focused). Thats being said, I found "magic" functionality on stackOverflow which will fix those focus issues anywhere in my app:
"Magic function":
override fun dispatchTouchEvent(event: MotionEvent): Boolean {
if (event.action == MotionEvent.ACTION_DOWN) {
val v = currentFocus
if (v is EditText) {
val outRect = Rect()
v.getGlobalVisibleRect(outRect)
if (!outRect.contains(event.rawX.toInt(), event.rawY.toInt())) {
v.clearFocus()
val imm = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
imm!!.hideSoftInputFromWindow(v.getWindowToken(), 0)
}
}
}
return super.dispatchTouchEvent(event)
}
I've tried to make some interceptor View
(for example FrameLayout
) which acts as touch detector. Then I've added onTouchListener
and used similar code as dispatchTouchEvent
function has. But this doesnt work. I've also tried to apply onTouchListener to my fragment rootView
but same result.
Example (in this case interceptor is FrameLayout
over my whole layout):
interceptor.setOnTouchListener { _, event ->
if (event.action == MotionEvent.ACTION_DOWN) {
val view = activity?.currentFocus
if (view is EditText) {
val outRect = Rect()
view.getGlobalVisibleRect(outRect)
if (!outRect.contains(event.rawX.toInt(), event.rawY.toInt())) {
view.clearFocus()
val imm = view.context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager?
imm!!.hideSoftInputFromWindow(view.getWindowToken(), 0)
}
}
}
false
}