"Go" event distribution and processing in Android

Source: Internet
Author: User

Original link: http://www.apkbus.com/home.php?mod=space&uid=705730&do=blog&id=61207

Last time I shared with you a little bit about custom view, this time to talk about the view of the event distribution and processing, why the theme is view, because as a junior application layer of Android engineers, I deal with the most than a variety of view, Only by learning more about their habits can you better communicate with them and make the results you want.

Base Reserve View, Motionevent

We can all say in detail the four components of Android: Activity,service,contentprovider and Boardcastreceiver, but there are a lot of things that we use in addition to the four components, which certainly include view, View is the user's communication with the application of the portal, but also the program to show the User Information window. On the view, some of the basic properties to understand, Left,top,right,bottom, respectively, represents the upper-left corner of the view and the lower-right corner respectively relative to the x-axis, y-axis coordinates, and the values of the view getwidth and getheight are calculated by these four values, And in the Android3.0 also added X,y,translationx and translationy These properties, easy for us to translate the view, X, y represents the upper left corner of the current view XY coordinates, While Translationx and translationy represent the offset of the view relative to its parent container, the default value is 0.

Motionevent represents a user's touch event, and a single click, touch, or swipe of the user produces a series of motionevent:

    • Motionevent.action_down indicates that the user's finger has just touched the screen
    • Motionevent.action_move indicates that the user's finger is moving
    • MOTIONEVENT.ACTION_UP indicates that the user's finger is lifted from the screen

So once the user touches the screen it may produce these events:

    • Tap the screen and release, Down->up
    • Tap the screen, then swipe a distance, release the screen, Down->move->...->move->up
      Having learned the basics, let's learn how to distribute these events
ViewGroup distribution, interception-and processing

First of all, although ViewGroup is also inherited view, but because in the event of interception, ViewGroup analysis more convenient to understand, so first say ViewGroup, the following will briefly introduce the View event processing.

In the event distribution process, there are three main methods involved:

  • Dispatchtouchevent (Motionevent event);
  • Onintercepttouchevent (Motionevent event);
  • Ontouchevent ();
    First look at these three methods there is a circle, if this time in the head drilling source, it is even more confused, I am here to borrow Ningyugang a large part of the pseudo-code to explain the relationship between the three:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    Dispatchtouchevent(Motionevent event) {
    False
    if (Onintercepttouchevent (event)) {
    consume = Ontouchevent (event);
    else {
    consume = Child.dispatchtouchevent (event);
    }

    return consume;
    }

    From this pseudo-code, we can see, in the Dispatchtouchevent, first call ViewGroup own Onintercepttouchevent method, determine whether they want to intercept, if this time to intercept themselves, Then call your own Ontouchevent method, if the Ontouchevent method returns True, then this time the event is consumed, event delivery ends, if False is returned, that this time did not consume this motionevent, Then this time the event will go up, continue processing from the previous level, if the current ViewGroup Onintercepttouchevent returns false, then it will call its child view of the Dispatchtouchevent method, This event is passed down, if its sub-view can not handle, then will return to call ViewGroup's Ontouchevent method, of course, this is not reflected in the pseudo-code, with a popular example to explain:

    The leader received a task (may be given by the superior), took a look at it, and then decided to take a good rest, today does not work, the task to the hands of the small Wang, Wang's default property is as long as the task to connect, and on the dry, capable can not do the same, if this is a simple task, then the small Wang This task is completed, unfortunately, this task Xiao Wang did not solve, and then to the leadership feedback, leadership no way, no one can solve, had to do their own work, began to solve the problem, and then resolved, the task has also been completed.

This is the ViewGroup layer of event distribution, of course, it is not so simple, it is only through a simple way to understand, in fact, in the real event distribution, there are many problems to note:

    • A completed sequence of events starts with a down, may contain several moves in the middle, and then ends with a
    • Once a view intercepts an event, the entire sequence of events where the current event is located will be handled by this view, in real code, once the view has intercepted the down event, Then the move and up events will not call Onintercepttouchevent, and it is directly handled by it, which also means that it is inappropriate to handle the event in Onintercepttouchevent, because it is possible to come up with an event, But skip the Onintercepttouchevent method directly. This also means that once a viewgroup does not intercept the Action_down, it will not receive any other action in the sequence of events, so it is especially prudent to handle action_down.
    • Ontouchevent is to judge Motionevent action, because one click operation will call two times Ontouchevent method, once is Action_down, once is action_up, if hand slip, There will be a number of action_move.
    • ViewGroup default does not intercept any events, the source code in the ViewGroup Onintercepttouchevent method returns the default is False

The entire event distribution appears to be passed from the outside, the parent view passes the event to the child view, in theory, the child view has no way to affect the parent view of the event processing, but there is a marker bit, Requestdisallowintercepttouchevent method, through this method, sub-view can affect the parent view of the event processing, this can be used to solve the parent view and child view of the sliding conflict, specifically want to know the relevant use of the search it, This will not be expanded.

The View only silently bear

View is different from ViewGroup, there is no Onintercepttouchevent method in view, because view as the last level of event processing, do not need to determine whether to intercept, it is necessary to intercept, regardless of can be processed, you have to try, So the calling process in view is:

Dispatchtouchevent-Ontouchevent

Also, the return value of the last Ontouchevent is true by default, that is, the event is passed down and will be consumed, just to see if someone is intercepted in the middle, this time the reader may have questions: TextView's ontouchevent return value is also true? The answer is: yes, why dot on the TextView or can trigger its parent view of the ontouchevent, theoretically should not be, TextView consume this event, do not return. This is true in theory, but because TextView's clickable and Longclickable properties are false, the event is not consumed when both properties are false, so textview does not consume events. This can also explain why you put a textview on a button, and then click TextView to trigger the button's Click event

Here may need to remind everyone, is a I stepped before a pit, I put a view of the enable State to false, and then added to it onclicklistener, this time I thought, its Click event will not be triggered, the result it can still be clicked, Later learned that the enable state of the view and ontouchevent is not related, only the clickable state is affected by ontouchevent, there is a point, set The view's enable false will also set the view's clickable to false, but setting the view's Onclicklistener will turn the view's clickable to true, So the final solution is to replace the two lines of code in order, the problem is solved.

Detailed processing Gesuturedetector

Arduous hardships, finally intercepted the incident, and then we need to do something, otherwise we can not afford to waste so much of their breath, talking about the handling of the incident, we first think of is Setonclicklistener, But Onclicklistener priority is the lowest, the next section will be on the priority of the description, and here, we will mainly think of if handling events, when we excited to get a series of events, but do not know how to start, even the simplest click events to do their own treatment, Not to mention panning, rotating, zooming, but the official gesturedetector provided us with the possibility.

The official gesturedetector is a gesture aid detection class that detects multiple gestures by default:

 1 
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
ClassSimplegesturelistenerImplementsGesturedetector.Ongesturelistener {
@Override
PublicBooleanOndown(Motionevent e) {
ReturnFalse
}

@Override
PublicvoidOnshowpress(Motionevent e) {

}

@Override
PublicBooleanOnsingletapup(Motionevent e) {
ReturnFalse
}

@Override
PublicBooleanOnscroll(Motionevent E1, motionevent E2,Float Distancex,Float Distancey) {
ReturnFalse
@Override
public void onlongpress< Span class= "params" > (motionevent e) {

Span class= "line" > @Override
public boolean onfling ( Motionevent E1, motionevent E2, float velocityx, float velocityy) {
Span class= "line" > return false;
}
/span>


Through this class, we can easily deal with the addition of click and long press, but also sliding, double-click and other gestures, and to deal with them separately, if these still do not satisfy your curiosity, there is an official offer of Scalegesturedetector, You can tell from the name. This is an auxiliary class to detect the reduction of the potential, but also Daniel modeled scalegesturedetector ideas to make a translation and rotation of auxiliary classes, and then we can be based on these auxiliary classes, almost do whatever it is, below I wrote a support for panning, zooming, Rotate the Little demo.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
PrivatevoidInit() {

Scalegesture =New Scalegesturedetector (GetContext (),New Scalelistener ());
Movegesture =New Movegesturedetector (GetContext (),New Movinglistener ());
Rotategesture =New Rotategesturedetector (GetContext (),New Rotatelistener ());

}

@Override
PublicBooleanOntouchevent(Motionevent event) {

Scalegesture.ontouchevent (event);
Movegesture.ontouchevent (event);
Rotategesture.ontouchevent (event);

ReturnTrue
}


PrivateClassScalelistenerImplementsScalegesturedetector.Onscalegesturelistener {

@Override
PublicBooleanOnscale(Scalegesturedetector detector) {

Setscalex (Detector.getscalefactor () * Getscalex ());
Setscaley (Detector.getscalefactor () * Getscaley ());

return true;
@Override
public boolean Onscalebegin (Scalegesturedetector detector) {
return true;
@Override
public void onscaleend< Span class= "params" > (Scalegesturedetector detector) {

}



Only part of the code, and seemingly rotating seems to be a bit of a problem, after the time to revise, useful to the reader can learn in detail, the complete code, I will give a link at the end of the article, but also thanks to the Android Multitouch gesture detectors author, Provides a handy gesture manipulation class

Ontouchlistener ontouchevent Onclicklistener

We must know Onclicklistener and Ontouchlistener before we know ontouchevent, and they are all consumers of the event, Ontouchlistener is in the Ontouch method, and Ontouch to Ontouchevent first, that is, once the Ontouchlistener is set and the last Ontouch method returns True, the ontouchevent will not be executed again. and Onclicklistener and ontouchevent have some relationship, Ontouchevent's default implementation will call Onclicklistener's OnClick method, if the ontouchevent is overridden, Because Onclicklistener accepts no action_down and action_up, then setting up Onclicklistener will no longer take effect, this time the click or long press processing can only be handled in Ontouchevent itself.

The End

Talk so much, mainly want to view the interception mechanism to understand a little more, because recently read Ningyugang big "Android Development Art Inquiry", the text also quoted a lot of ideas in the book, want to know more small partners can buy a read, benefited, to a JD link, JD Portal

SOURCE Address: GitHub link

"Go" event distribution and processing in Android

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.