Touch event Distribution mechanism

Source: Internet
Author: User

Simple analysis of Android's touch event distribution mechanism

Reference:http://www.cnblogs.com/linjzong/p/4191891.html

There are only two main characters in touch event distribution: ViewGroup and view. The activity's touch event is actually called the ViewGroup touch event inside it, and can be treated directly as ViewGroup.

View within the ViewGroup, ViewGroup can also be in other viewgroup, this time the internal viewgroup as a view to analyze.

There are three related events in ViewGroup: Onintercepttouchevent, Dispatchtouchevent, Ontouchevent. There are only two related events for view: Dispatchtouchevent, Ontouchevent.

First analyze the ViewGroup process: first, there must be a structural model concept: ViewGroup and view constitute a tree structure, the top of the activity of the viewgroup, there are a number of viewgroup nodes, There are several ViewGroup nodes or view nodes under each node, and so on.

When a touch event (for example, a touch event) reaches the root node, the acitivty ViewGroup, it is issued sequentially, and the process is implemented by invoking the Dispatchtouchevent method of the Child view (ViewGroup). Simply put, viewgroup iterates through the child view it contains, invokes the Dispatchtouchevent method of each view, and when the child view is ViewGroup, The Dispatchtouchevent method of its internal view is resumed by calling Viwgroup's Dispatchtouchevent method. The order of the messages in the above example is this: ①-②-⑤-⑥-⑦-③-④. The Dispatchtouchevent method is only responsible for the distribution of the event, which has a Boolean return value, and when returned to true, the order is interrupted. In the above example, if ⑤ 's Dispatchtouchevent returns True, ⑥-⑦-③-④ will not receive this touch event.

Multi-Touch

Objective

The distribution of touch events in Android is a worthwhile thing to study. I didn't see you. introduced a ListView slide function, the ListView does not listen to the fingers of your finger to scroll, do not know why the button set the onclick and Ontouch, who will first respond to Perhaps you will ask what is the difference between Ontouch and ontouchevent, and how to use it? Everything here, as long as you understand the event distribution mechanism, you will find that explaining this is not a thing!

Ontouch and Ontouchevent differences

Reference: http://blog.csdn.net/huiguixian/article/details/22193977

    1. Ontouchlistener's Ontouch method has a higher priority than ontouchevent, which is triggered first.
    2. If the Ontouch method returns False, then the ontouchevent is triggered, and the Ontouchevent method is not called.
    3. Built-in implementations such as the Click event are based on Ontouchevent, and if Ontouch returns True, these events will not be triggered.

OnClick and Ontouch differences

Reference: http://blog.csdn.net/mydreamongo/article/details/30465613

Long Press and click

How to Relate touch events

1. Public boolean dispatchtouchevent (motionevent ev) ———— event distribution method, which is called by the

2. Public boolean onintercepttouchevent (motionevent ev) ———— event interception method to intercept the call

3, public boolean ontouchevent (Motionevent event) ———— Event response method, handling the call

Classes that have the above events

1. Activity class (activity and its various inheriting subclasses)

Dispatchtouchevent (), Ontouchevent ()

2, ViewGroup class (LinearLayout, Framelayout, ListView, etc..... )

Dispatchtouchevent (), Onintercepttouchevent (), Ontouchevent ()

3. View Class (Button, TextView, etc...) )

Dispatchtouchevent (), Ontouchevent ()

PS: One thing that needs special attention is that ViewGroup has an extra onintercepttouchevent () method, and the other two methods are common to these three species.

Simple use resolution of the method

We can see that the return values of these three methods are all Boolean types, but they are the return values that determine the direction of the next pass processing.

1, Dispatchtouchevent ()--used to distribute the event

This method distributes the events of the root element from top to bottom into the inner child element until it is terminated or arrives at the innermost element, which is also distributed using a tunneling method. in which onintercepttouchevent () and ontouchevent () are called, they are not generally rewritten.

Returns false to not intercept the continuation of the distribution, if true to intercept the event is not distributed in the downward layer element, in the Dispatchtouchevent () method by default returns False.

2, Onintercepttouchevent ()--Used to intercept the event

The implementation of this method in the ViewGroup source code is to return false to not intercept the event, and the touch event is passed down to its child view.

If we override the method and return it to true, the event will be intercepted and processed by the current viewgroup, calling the class's Ontouchevent () method.

3, Ontouchevent ()--For handling events

Returns true to indicate that the view can handle the event, and the event terminates the pass-up (passed to its parent view)

Returns false to indicate that it cannot be processed, then the event is passed to its parent view's Ontouchevent () method to handle

Practical Walkthrough

OK, the basic knowledge is finished, the above things do not understand it does not matter, now to open big eyes to look good, because the following began to use examples to explain the touch of the event distribution mechanism, I believe you can better understand this distribution mechanism.

In this example, we need to rewrite four classes:

1, Boss--myactivity

2, manager--Framelayout

3. Group Leader---Linealayout

4, employee--TextView

The software interface diagram is as follows:

" start with an easy-to-understand example. "

The boss said to the minister: I want to eat braised fish minister said to the manager: You do a braised fish manager said to the team leader: You do a braised fish leader to the staff said: you make a braised fish ... (Employees do, do not burn the fish out) employees said: I have to work overtime or did not do it, do not deduct my salary line leader said: You idiot, white hair your wages, next time you do not find, I do ... (The team leader did, or did not do) the leader said to the manager: "I tried, or did not do it, do not fire me squid Ah manager said:" You a waste, this is not good, only I have to do ... (The manager did it, he did it.) The manager said to the minister: Braised Fish Well, the minister responded: "Good, next time you have to find you minister to the boss said:" Braised fish do the boss responded: "Good, next time you have to find you --------------------------- The boss said to the minister: "I want the water boiled fish minister to the manager said:" You do a boiled fish manager himself think: The team leader even braised fish can not make, this time not to find him, I personally to do ... (The manager did it, he succeeded again) the manager said to the minister: Braised Fish Well, the minister responded: "Good, next time you have to find you minister to the boss said:" Braised fish do the boss responded: "Good, next time you have to find you ---------------------------

1, according to common sense, the leadership will be assigned to the task downward, once the following people do not do well, will not be the follow-up task to the following people to do, can only do their own, if they can not do, can only tell the superior can not complete the task, the superior will repeat his process.

2, in addition, the leadership has the right to intercept the task, the subordinate to conceal the task, and directly to do, if not done, can only report to the superior can not complete the task.

Process Demo

"1", we assume that the staff capacity is insufficient, that is, the TextView ontouchevent () method setting returns False, indicating that it cannot consume the event.

Process for event Delivery:

"2", we assume that the employee can handle the event, that is, the TextView's Ontouchevent () method setting returns True, indicating that it can handle the event.

?

Process for event Delivery:

"3", we assume that the staff and team leader ability is insufficient, namely TextView and LinearLayout's Ontouch () return false, but the manager resolved the problem, that is, Framelayout Ontouch () returns True

Process for event Delivery:

"4" Suppose our leader, when the event was distributed to him, decided to intercept it and not give it to the following employee, that is, Onintercepttouchevent () returned to true, and he completed the task successfully, that is, the ontouchevent () return value is true.

Process for event Delivery:

Make a summary.

1, it is clear that these processes are the result of dispatchtouchevent (), but only if we do not fully re-implement this method, that is, to ensure that the return super.dispatchtouchevent (EV); To determine if a method of the parent class has been called. These events will be passed from top to bottom, until passed to the bottommost view element, which will call the view's Ontouchevent () method to handle the event, and true to indicate that the event has been successfully processed and that if False is returned, the event is not successfully processed. The event will be passed up and down to the upper view's Ontouchevent () method, and so on, until a view successfully processes the event, or the top view processing still returns false to discard the event processing, and the event disappears.

2, if the event is passed down in the process, is intercepted, that is, the view of the Onintercepttouchevent () method returns True, then the event will stop passing down and handed over to the layer's ontouchevent () method processing, regardless of the processing success or not, The underlying view will no longer receive the event. PS: If processing fails, it will be processed by the Ontouchevent () method of the upper view.

3, Dispatchtouchevent () has the function of memory, if the first event is passed down to a view, it continues to pass the event to its child view, it will record whether the event is processed by the view below it successfully, (how can you know?) If the event is passed up again to me here for my ontouchevent (), it means that the view below is not able to handle the event successfully); When the second event is passed down to the view, the view's Dispatchtouchevent () Method opportunity to judge, if the last event was successfully processed by the following view, then the event will continue to the following to deal with, if the last event is not successfully processed by the following, then this event will not be passed down, the view directly call their own ontouchevent () method to handle the event.

4, Memory function information is only valid before a series of events, such as starting from the Action_down event, until the end of the subsequent event action_move,action_up, "Memory" information will be cleared. That is, if a view processing Action_down event fails (Ontouchevent () returns false), subsequent events such as ACTION_MOVE,ACTION_UP are no longer passed to the view, which is handled by the parent view itself. The next time the Action_down event occurs, it will still be delivered to the view.

Included code

1, MyActivity

 Public classMyActivityextendsactionbaractivity {@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate);    Setcontentview (R.layout.activity_main); } @Override Public Booleandispatchtouchevent (motionevent ev) {LOG.I ("Test", "Boss" Release task: "+ util.actiontostring (ev.getaction ()) +", find someone to help me complete, the task is distributed down. "); return Super. dispatchtouchevent (EV); } @Override Public Booleanontouchevent (Motionevent event) {BooleanRelust =false; LOG.I ("Test", "Boss" to complete the task: "+ util.actiontostring (event.getaction ()) +", "manager" is too bad, no longer looking for you to work, I came to take care of! Whether to resolve: "+util.candotasktop (relust)); returnRelust; }}
View Code

2, Myframelayout:

 Public classMyframelayoutextendsFramelayout { PublicMyframelayout (Context context, AttributeSet attrs) {Super(context, attrs); } @Override Public Booleandispatchtouchevent (motionevent ev) {LOG.I ("Test", "manager" to release the task: "+ util.actiontostring (ev.getaction ()) +", find someone to help me complete, the task is distributed down. "); return Super. dispatchtouchevent (EV); } @Override Public Booleanonintercepttouchevent (motionevent ev) {BooleanRelust =false; LOG.I ("Test", "Manager" interception task: "+ util.actiontostring (ev.getaction ()) +", stop it? " +relust); returnRelust; } @Override Public Booleanontouchevent (Motionevent event) {BooleanRelust =true; LOG.I ("Test", "manager" to complete the task: "+ util.actiontostring (event.getaction ()) +", "team Leader" is too bad, no longer looking for you to work, I came out! Whether to resolve: "+Util.candotask (relust)); returnRelust; }}
View Code

3, Mylinearlayout

 Public classMylinearlayoutextendsLinearLayout { PublicMylinearlayout (Context context, AttributeSet attrs) {Super(context, attrs); } @Override Public Booleandispatchtouchevent (motionevent ev) {LOG.I ("Test", "Team Leader" Release task: "+ util.actiontostring (ev.getaction ()) +", find someone to help me complete, the task is distributed down. "); return Super. dispatchtouchevent (EV); } @Override Public Booleanonintercepttouchevent (motionevent ev) {BooleanRelust =true; LOG.I ("Test", "leader" whether intercept task: "+ util.actiontostring (ev.getaction ()) +", stop it? " +relust); returnRelust; } @Override Public Booleanontouchevent (Motionevent event) {BooleanRelust =true; LOG.I ("Test", "team Leader" to complete the task: "+ util.actiontostring (event.getaction ()) +", "staff" is too bad, no longer looking for you to work, I came through! Whether to resolve: "+Util.candotask (relust)); returnRelust; }}
View Code

4, Mytextview

 Public classMytextviewextendsTextView { PublicMytextview (Context context, AttributeSet attrs) {Super(context, attrs); //TODO auto-generated Constructor stub} @Override Public Booleandispatchtouchevent (Motionevent event) {log.i ("Test", "Employee" Release task: "+ util.actiontostring (event.getaction ()) +", I have no men, alas ~ do it yourself); return Super. Dispatchtouchevent (event); } @Override Public Booleanontouchevent (Motionevent event) {BooleanRelust =false; LOG.I ("Test", "staff" to complete the task: "+ util.actiontostring (event.getaction ()) +", "Employees" now only on their own! Whether to resolve: "+Util.candotask (relust)); returnRelust; }}
View Code

5. Util (Tool Class)

 Public classUtil { Public StaticString actiontostring (intaction) {String result=NULL; Switch(action) { CaseMotionEvent.ACTION_DOWN:result= "Action_down";  Break;  CaseMotionEvent.ACTION_MOVE:result= "Action_move";  Break;  CaseMotionEvent.ACTION_UP:result= "Action_up";  Break; }        returnresult; }     Public StaticString Candotask (Booleancan) {String result=NULL; if(CAN) {result= "Perfect solution to the task!" "; }        Else{result= "This is not going to work, give the boss to finish it." "; }        returnresult; }     Public StaticString Candotasktop (Booleancan) {String result=NULL; if(CAN) {result= "Perfect solution to the task!" "; }        Else{result= "This is not going to work, give up the task." "; }        returnresult; }}
View Code

Touch event Distribution mechanism

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.