This is a repost of an answer I wrote on Stack Overflow.
When a user touches the screen, who gets notified of the touch? In what order are views notified?
Let’s take a look at a visual example.
When a touch event occurs, first everyone is notified of the event, starting at the Activity and going all the way to the view on top. Then everyone is given a chance to handle the event, starting with the view on top and going all the way back to the Activity. So the Activity is the first to hear of it and the last to be given a chance to handle it.
If some ViewGroup wants to handle the touch event right away (and not give anyone else down the line a chance at it) then it can just return
true in its
onInterceptTouchEvent(). An Activity doesn't have
onInterceptTouchEvent() but you can override
dispatchTouchEvent() to do the same thing.
If a View (or a ViewGroup) has an
OnTouchListener, then the touch event is handled by
OnTouchListener.onTouch(). Otherwise it is handled by
true for any touch event, then the handling stops there. No one else down the line gets a chance at it.
More detailed explanation
The above diagram makes things a little more simple than they actually are. For example, between the Activity and ViewGroup A (the root layout) there is also the Window and the DecorView. I left them out above because we generally don’t have to interact with them. However, I will include them below. The description below follows a touch event through the source code. You can click a link to see the actual source code.
(Update: the source code has been updated so the line numbers are off now, but clicking the links will still get you to the right file. Just do a search for the method name.)
- The Activity’s
dispatchTouchEvent()is notified of a touch event. The touch event is passed in as a
MotionEvent, which contains the x,y coordinates, time, type of event, and other information.
- The touch event is sent to the…