A deep understanding of the event transfer mechanism of the View, and a deep understanding of the view

Source: Internet
Author: User

A deep understanding of the event transfer mechanism of the View, and a deep understanding of the view

Introduction: Currently, there are more and more cool Android controls on GitHub. On the one hand, we can make the App look beautiful, and on the other hand, we developers can learn a variety of knowledge from it. Write this blog post to record the knowledge blind spots that are exposed in the process of studying the source code of a custom control and help you consolidate your knowledge. At the same time, you can also learn and make progress together.

Demo source code

If you don't talk nonsense, go to the topic:

1. Overview of View event Transfer Mechanism

Interaction between users through clicks, sliding screens, and apps is the basis of interaction in the mobile Internet era. In Android, how does a user's clicks and slides interact with the Android system?

In Android, what we call click, slide, and other events are regardedMotionEventIn MotionEvent, our operation behavior is classified as the following constant:

  • ACTION_DOWN
  • ACTION_UP
  • ACTION_MOVE
  • ACTION_POINTER_DOWN
  • ACTION_POINTER_UP
  • ACTION_CANCEL

In addition, in order for the system to better manage and operate these events, MotionEvent also needs to record the event occurrence time and determine whether the event is a single-touch, multi-touch, and event occurrence time. Some may ask, is this constant enough for us to judge our gestures? Mo panic, but Google has a clear distinction between events: a touch operation starts with ACTION_DOWN and finally ACTION_UP. Simple touch operations, such as click and slide operations, can be easily identified through these constants. Complex gestures, you need to constantly analyze the event coordinates based on the sliding track of your fingers.

Note: to simplify understanding, I will classify all the events related to clicks, slides, and so on as click events.

Ii. View event Transfer Process

The subsequent parsing will be carried out in combination with the source code, and those with no foundation should keep up with them.

In Android, when a click event is passed in, first run the dispatchTouchEvent () method of Actvity to receive the event, after an event is received by the Activity, it is distributed to the root layout (that is, the layout in the Window associated with the Activity, usually ViewGroup, such as common LinearLayout and RelativeLayout, if the root layout does not need to handle this event, unless a layout intercepts the event through the onInterceptTouchEvent () method during the transfer process, and "consume" the event (the concept of consumption will be explained through the source code below), otherwise the event will be passed down to the sub-layout. If the event is still not processed in the sub-layout at the bottom layer, it will be passed up in turn. At this time, each parent layout can process the event. If the event is returned to the root layout, the event is terminated by the onTouchEvent () method of the Activity.

Note: OnTouchListener takes precedence over onTouchEvent ()

Looking at such a large description, it is estimated that many of our friends are dizzy. In fact, they are also dizzy ~ For your better understanding, I will first use a Demo to introduce this concept and parse the source code:

The Demo code is very simple, that is, custom buttons and LinearLayout. logs are output when related methods are executed, and logs are output when related methods are executed in the Activity. Click Process

The View event transfer process we just explained is well elaborated. Let's take a look at the source code below to learn more about the mechanism:

First, judge the event in the dispatchTouchEvent () method of the Activity (two judgment statements are not required), and then enter the onTouchEvent () method.

    public boolean dispatchTouchEvent(MotionEvent ev) {        if (ev.getAction() == MotionEvent.ACTION_DOWN) {            onUserInteraction();        }        if (getWindow().superDispatchTouchEvent(ev)) {            return true;        }        return onTouchEvent(ev);    }

There is a judgment in the onTouchEvent () method. shouldCloseOnTouch () is used to determine whether the event is returned from the end. true indicates that the event should not be passed down, and false indicates that the event is not consumed, it should be passed down and handed over to the sub-layout for processing.

Therefore, the concept of "consumption" that we have just mentioned is this. If an event is passed back and forth on the View chain, as long as it is processed and its View is processed, false is returned, we think that the event is consumed. If true is returned, we think that the event has not been consumed and still need to be passed down to let the corresponding View process it.

    public boolean onTouchEvent(MotionEvent event) {        if (mWindow.shouldCloseOnTouch(this, event)) {            finish();            return true;        }        return false;    }

Now MyLinearLayout receives events through the dispatchTouchEvent () method. We only click in the Demo. The dispatchTouchEvent () method involves moving and up, so I will only extract the part related to down to explain it.

// Check for interception.    final boolean intercepted;    if (actionMasked == MotionEvent.ACTION_DOWN            || mFirstTouchTarget != null) {        final boolean disallowIntercept = (mGroupFlags & FLAG_DISALLOW_INTERCEPT) != 0;        if (!disallowIntercept) {            intercepted = onInterceptTouchEvent(ev);            ev.setAction(action); // restore action in case it was changed        } else {            intercepted = false;        }    } else {        // There are no touch targets and this action is not an initial down        // so this view group continues to intercept touches.        intercepted = true;    }

The logic is simple, right? First, determine whether to intercept the event. If you want to intercepted the event, set intercepted to true so that the subsequent return value is also true, so that the event is consumed by the current View. If you do not intercept the event, the event will continue to be passed down.

The same applies to the MyButton.

Several images are displayed on the Internet to demonstrate the entire process well:



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.