This article aims to give you a big picture regarding how the touch event is handled in Android. Simply speaking , we are trying to answer the question: when I press a button in an app , how the touch event is dispatched to that button and how can I handle it?
A picture is worth a thousand words. Therefore, I come up with the one below. The left diagram is what we see as a normal user ; the right one illustrates how the views are organized as a tree ; the bottom one describes the pipeline of event dispatching and handling, from Input module down to the individual focused view.
I wish the diagram is self explaining, and I'd stress a few key points:
|view hierarchy and touch event handling pipeline|
3. Child view take precedence over parent view in handling event. Only if the child view does not consume the event, parent view can have a chance to handle it. In diagram above , if steps 6 return false, contenview will call its owner onTouchEvent, that is step 7. See ViewGroup::dispatchTouchEvent() below.
5. If none of the views in the content view hierarchy handles the touchEvent, Activity::onTouchEvent will have a chance to handle it. see Activity::dispatchTouchEvent() below.
Below are implementation of dispatchTouchEvent in View, Activity and ViewGroup. Code are pruned for simplicity.
To reiterate what we talked, I captured the stacks when the button was touched. From this call stack we can confirm the touch event dispatched from the window -> activity -> viewGroup.dispatchTouchEvent -> view.dispatchTouchEvent ->view.onTouchEvent as we described previously. Then the call stack will wind back.
|event handling call stack|
I hope this introduction will make you more confident when dealing with the touch event in Android.