Android event processing mechanism

Source: Internet
Author: User
Tags gety

Android event processing mechanism

When talking about android event processing, the most complex thing is the processing of Touch events, because Touch events include: down, move, up, cancle, multi-Touch, and many other situations, we will not discuss the situation of multi-Touch, because Touch has so many States, it is relatively difficult to handle. Next we will discuss how the android system handles Touch events.

1. when it comes to event processing, we must first understand why we need to process events and how the android system processes events. in actual development, if we use the basic controls of the system, we do not need to process events. However, if we use complicated layout nesting to implement some special requirements, such: nested ListView in ScrollView and nested ViewPager in ScrollView generate event conflicts. Therefore, due to the existence of event conflicts, we have to deal with these conflicts. We only need to understand the android event processing mechanism, in order to effectively handle event conflicts. in addition, if we want to develop a new component, all the events of the component must be handled by ourselves. In this case, we also need to handle the event. therefore: because of the two situations mentioned above, we have to handle the event on our own.

2. with the motivation to process events, we need to understand how the android system handles complex events. the android system provides three related methods for all events. The following uses Touch events as an example to describe.

The three methods are:

DispatchTouchEvent (MotionEvent ev); (this method is available for Activity, ViewGroup, and View)

OnInterceptTouchEvent (MotionEvent ev); (only available in ViewGroup)

OnTouchEvent (MotionEvent); (this method is available for Activity, ViewGroup, and View)

To understand how the android system handles events step by step, these three methods must be mastered. among them, the dispatchTouchEvent (MotionEvent ev) method is used to distribute events to the target control, and the onInterceptTouchEvent (MotionEvent ev) method is used to filter events, that is, to intercept an event, that is, whether to pass down the event, onTouchEvent (MotionEvent ev) is used to process the event. That is to say, when we override onTouchEvent, in fact, the system has already called the first two methods by default. the following describes the three methods in detail.

The first thing to mention is that the android system processes this item layer by layer (tree processing ). where does this tree come from .. it is our layout tree, a layout. Whether it is the layout of code writing or the layout generated by xml, the android system assembles it into a UI tree when parsing it, the layout of the outermost layer is the root of the entire UI tree. after knowing this, analyze the event processing.

Processing Process: when our fingers Touch the mobile phone screen, the current onStart () Activity first receives the ACTON_DOWN under this Touch event, and then starts to call its own dispatchTouchEvent () start DOWN event distribution. If this method returns true, the Activity does not distribute the event downward, and the entire layout will not receive the DOWN event. The TouchEvent is directly sent to the onTouchEvent () of the Activity () method for event processing. if false is returned, the DOWN event is distributed to the lower layer. In this case, the DOWN event is directly distributed (because there is no filtering method) to the root layout of the UI tree (that is, the layout of the outermost layer), when the root layout gets the DOWN event, execute its own dispatchTouchEvent method and return true, then the event is directly handed to the onTouchEvent () of the root layout () if it is false, it indicates that the event has to be distributed downward. At this time, the event is passed to the onInterceptTouchEvent () method of the root layout. If this method returns true, it indicates that the event is to be filtered, this DOWN event is directly processed by the onTouchEvent () method in the root layout. If it is false, the root layout will not filter the event, and the DOWN event will continue to be passed DOWN, after the target component is reached, the target component calls its own dispatchTouchEvent () method. Because it is a target component, the event is directly distributed to its onTouchEvent method, if the target component returns true after processing the DOWN event, it indicates that the event has been consumed and will not be passed up. If false is returned, it indicates that the DOWN event has not been consumed, the DOWN operation is passed up to its parent component, and the parent component then processes the DOWN event. always pass up until the event is thrown to the VM. the DOWN event is regarded as processing completed, and then the MOVE operation is called. After the MOVE operation is finished, the entire process is the same as the DOWN operation.

It should be emphasized that, if a component does not receive the DOWN event, it will not receive the MOVE or UP event.


Through the above process, we can understand that the android system handles any event in this way. It distributes events, filters events, processes events, next events, distributes events, and filters events, handling events ...... This way all events are processed cyclically. That is, event distribution, filtering from the root to the leaf, and processing from the leaf to the root.

Below is a process flow chart that I drew from the above text flow:


As shown in the figure, we can more intuitively feel the processing flow of the entire Touch event.


<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + kernel + 1zbPKx8jnus60psDtysK8/kernel/sTYoa2hrc/Cw + a9q87S1q7HsLSmwO25/kernel + kernel/Co7o8L3A + kernel "brush: java;"> package com. micen. buyers. view. category; import android. content. context; import android. util. attributeSet; import android. util. log; import android. view. motionEvent; import android. widget. scrollView; import com. micen. buyers. util. util; public class MyScrollView extends ScrollView {private float mLastMotionY; private float mLastMotionX; public MyScrollView (Context context, AttributeSet attrs) {super (context, attrs ); // TODO Auto-generated constructor stub}/*** rewrite this method to process the event */@ Overridepublic boolean dispatchTouchEvent (MotionEvent ev) {// TODO Auto-generated method stubfinal float x = ev. getX (); final float y = ev. getY (); switch (ev. getAction () {case MotionEvent. ACTION_DOWN: mLastMotionX = x; mLastMotionY = y; break; case MotionEvent. ACTION_MOVE: if (Math. abs (y-mLastMotionY)> Util. dip2px (20) & Math. abs (x-mLastMotionX) <Util. dip2px (5) {return true; // if the vertical coordinate of the MOVE event is greater than 20px and smaller than 5dp horizontally, the MOVE event is regarded as sliding scrollview. If true is returned, the event is not distributed downward, directly input to // onTouchEvent method. Otherwise, the sliding event is considered not to be processed by scrollview and can be distributed} break; case MotionEvent. ACTION_UP: break; case MotionEvent. ACTION_CANCEL: break;} return super. dispatchTouchEvent (ev) ;}@ Overridepublic boolean onInterceptTouchEvent (MotionEvent ev) {// TODO Auto-generated method stubreturn super. onInterceptTouchEvent (ev);} @ Overridepublic boolean onTouchEvent (MotionEvent ev) {Log. e ("--------->", "user want to scroll"); return super. onTouchEvent (ev );}}In the above Code, we overwrite the dispatchTouchEvent () of ScrollView to achieve a special processing of the event. If our rules are met, it will be processed directly in onTouchEvent (). Otherwise, the event is sent to onInterceptTouchEvent () for filtering. Because there is no filtering in this method, the event is delivered.

In the same effect, we start from the leaf to handle event conflicts. The Code is as follows:

Package com. micen. buyers. view. category; import android. content. context; import android. OS. handler; import android. OS. message; import android. util. attributeSet; import android. view. motionEvent; import com. micen. buyers. util. util; public class MyViewPager extends ViewPager {private boolean flag = true; private float mLastMotionY; private float mLastMotionX; public MyViewPager (Context context) {super (context );} public MyViewPager (Context context, AttributeSet attrs) {super (context, attrs) ;}@ Overridepublic boolean dispatchTouchEvent (MotionEvent ev) {final float x = ev. getX (); final float y = ev. getY (); switch (ev. getAction () {case MotionEvent. ACTION_DOWN: setPullToScrollViewStatus (true); // by default, the parent control does not receive sliding events. The events are directly transmitted to the Child slide component flag = true; mLastMotionX = x; mLastMotionY = y; mHandler. sendEmptyMessage (1); break; case MotionEvent. ACTION_MOVE: if (flag) {if (Math. abs (y-mLastMotionY)> Util. dip2px (20) & Math. abs (x-mLastMotionX) <Util. dip2px (5) {flag = false; setPullToScrollViewStatus (false); // if conditions are met, the parent slide control filters out the event and no longer uploads it to ViewPager .}} break; case MotionEvent. ACTION_UP: setPullToScrollViewStatus (false); case MotionEvent. ACTION_CANCEL: setPullToScrollViewStatus (false); break;} return super. dispatchTouchEvent (ev) ;}@ Overridepublic boolean onInterceptTouchEvent (MotionEvent event) {return super. onInterceptTouchEvent (event);} @ Overridepublic boolean onTouchEvent (MotionEvent event) {return super. onTouchEvent (event);} private void setPullToScrollViewStatus (boolean disallowIntercept) {// call the evaluate () method of the parent control and pass in "true". The onTInterceptTouchEvent of the parent control returns false, // do not filter. Otherwise, the parent control filters out events and does not pass them down. getParent (). getParent (). requestDisallowInterceptTouchEvent (disallowIntercept );}}

Conclusion: The android event processing process should be mastered by every android developer.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.