Member-only story
Android Touch System — Part 1: Touch Functions and the View Hierarchy
Without a deep understanding of how Android views handles touches, a lot of touch behaviours seem confusing. Why is this button click not working? Why is that RecyclerView
not scrolling? How do I handle nested ScrollView
s?
This article covers how touch events flow through the view hierarchy, and how a few core functions affect the flow. Part 2: Common Touch Event Scenarios shows concrete, visual examples of how these functions.
Table of Contents
- Background Knowledge
- dispatchTouchEvent
- onInterceptTouchEvent
- onTouchEvent
- requestDisallowInterceptTouchEvent
Background Knowledge
MotionEvent
Every movement on the touch screen is reported as a MotionEvent
object. The MotionEvent
class has getters for accessing all the information associated with the event. Some commonly-used ones are:
action
(the type of action being performed, more on this later)x
(x-coordinate of touch, relative to the view that handled it)y
(y-coordinate of touch, relative to the view that handled it)rawX
(absolute x-coordinate of touch, relative to the device screen)rawY
(absolute y-coordinate of touch, relative to the device screen)eventTime
(the time the event occurred, in theSystemClock.uptimeMillis()
time base)
Screen coordinates
As a reminder, Android screen coordinates are measured in pixels with x = 0 and y = 0 in the top left corner of the screen and the x = maxX and y = maxY in the bottom right corner.
Action
MotionEvent
’s getAction()
returns an Int
constant representing different action types. The full list can be found here, but here are some of the most common ones:
ACTION_DOWN
: When finger or object first comes in contact with the screen. The event contains the initial starting location of a gesture.ACTION_UP
: When finger or object lifts from the…