Interview frequency: …
Short answer
You control the touch path through dispatchTouchEvent, the container decides to intercept through onInterceptTouchEvent, while the View handles the actual touch in onTouchEvent.
Explanation
The user's touch begins at the top of the tree and goes down to the children through dispatchTouchEvent. A ViewGroup can inspect the touch and intercept it by returning true from onInterceptTouchEvent (such as the scroll motion in a ScrollView), which sends an ACTION_CANCEL event to the current child and directs the rest of the events to the container's own onTouchEvent. A child can also ask that the touch not be intercepted through requestDisallowInterceptTouchEvent(true).
Code example
override fun onInterceptTouchEvent(ev: MotionEvent): Boolean {
return when (ev.actionMasked) {
MotionEvent.ACTION_MOVE -> shouldInterceptScroll(ev) // Intercept scrolling
else -> false
}
}
override fun onTouchEvent(event: MotionEvent): Boolean {
// Run the actual drag animation
return gestureDetector.onTouchEvent(event)
}Common mistakes
- Unintentionally returning true on ACTION_DOWN inside onInterceptTouchEvent, which prevents the children from receiving any click events at all.