respect for the original:http://blog.csdn.net/yuanzeyao/article/details/37961997
Recently always encountered the problem of Android touch events, such as: the problem of sliding conflict, before also spent time to learn the transmission mechanism of Android touch event, you can always forget the time of use, simply to summarize their own writing article to avoid forgetting later, In fact, the internet about the transmission of touch events really a lot, but very few systematic, are written a simple demo run a bit, for our understanding of Android touch events basically no help.
Today I intend to analyze the transmission mechanism of the touch event from the source point of view. Before you know the touch event, it's a good idea to understand the process of creating windows in Android so that you know more about the overall structure of the android window and the way events are passed.
I will set the beginning of the event in the Phonewindow in the Decorview bar, as to who the incident to Decorview we do not have to care about it first. (If you want to delve into it, read one of my other articles on the key event delivery mechanism in Android) we just need to know that it's home is through the Dispatchtouchevent method to distribute the event to Decorview on the line, I went to the method to see what it is.
It's best to read the android window creation process before reading
@Override Public Boolean dispatchtouchevent (motionevent ev) { //The callback is the Decorview-affiliated activity, Can see my other article "The creation process of windows in Android" final Callback cb = Getcallback (); If Cb!=null && mfeatureid<0 executes the Dispatchtouchevent method in activity, <span style= "White-space:pre" for the application window ></span> //These two conditions are generally satisfied with the return CB! = NULL && Mfeatureid < 0? cb.dispatchtouchevent (EV): Supe R . dispatchtouchevent (EV); }
in Decorview, events are distributed to the activity through the Dispatchtouchevent method, believing that activity is no stranger to every Android developer, Then we'll go into the dispatchtouchevent method of activity.
public boolean dispatchtouchevent (motionevent ev) { if (ev.getaction () = = Motionevent.action_down) { Onuserinteraction (); } What does GetWindow return? If you read my "Windows creation process in Android" and know that Phonewindow, if the Superdispatchtouchevent method in Phonewindow returns true,// The touch event is then consumed by Phonewindow, no longer passed, and if it returns false, the activity's Ontouchevent method if (GetWindow () is executed. Superdispatchtouchevent (EV)) { return true; } return ontouchevent (EV); }
Enter the Superdispatchtouchevent method in Phonewindow:
@Override Public Boolean superdispatchtouchevent (Motionevent event) {//mdecor is a decorview type variable return Mdecor.superdispatchtouchevent (event); }
Enter the Superdispatchtouchevent method in Decorview:
public boolean superdispatchtouchevent (Motionevent event) {//Call the Dispatchtouchevent method of the parent class directly return Super.dispatchtouchevent (event); }
Come here we pause first, will look at the Decorview class Dispatchtouchevent method, if callback is not empty, then call callback Dispatchtouchevent method, Otherwise call the Super.dispatchtouchevent method, but the callback is not empty under the condition of the most also called to the Super.dispatchtouchevent method, then its super is which, we continue to look down:
through the source we can see that Decorview is inherited from Framelayout. So the event is finally passed to the Framelayout dispatchtouchevent, framelayout This method is inherited from the viewgroup, we go directly to the ViewGroup to see this method:
@Override public boolean dispatchtouchevent (Motionevent ev) {final int action = Ev.getaction (); Final float XF = Ev.getx (); Final float YF = ev.gety (); Final float scrolledxfloat = xf + mscrollx; Final float scrolledyfloat = YF + mscrolly; Final Rect frame = mtemprect;//can set the value of the variable by means of the Requestdisallowintercepttouchevent method, usually false Boolean disallowintercept = (Mgroupflags & flag_disallow_intercept)! = 0; if (action = = Motionevent.action_down) {if (mmotiontarget! = null) {//This is weird, we got a Pen down, but we thought it is//already down! Xxx:we should probably send a action_up to the current/target. Mmotiontarget = null; }//If we ' re disallowing intercept or if we ' re allowing and we didn ' t//Intercept//onintercepttouc Hevent returns false by default, so it is usually possible to go in if (disallowintercept | |!oniNtercepttouchevent (EV)) {//Reset this event ' s action (just to protect ourselves) ev.setact Ion (Motionevent.action_down); We know we want to dispatch the event down, find a child//who can handle it, start with the Front-most Child. Final int scrolledxint = (int) scrolledxfloat; Final int scrolledyint = (int) scrolledyfloat; Final view[] children = Mchildren; Final int count = mchildrencount;//Traverse viewgroup Child, if the touch point is in a child view, then the dispatchtouchevent for (int i =) in the child view is called. count-1; I >= 0; i--) {final View child = Children[i]; if (child.mviewflags & visibility_mask) = = VISIBLE | | child.getanimation () = null) { Child.gethitrect (frame); if (Frame.contains (Scrolledxint, Scrolledyint)) {//offset the event to the View ' s coordinate system final float XC = scrolledxfloat-child.mleft; Final float YC = scrolledyfloat-child.mtop; Ev.setlocation (XC, YC); Child.mprivateflags &= ~cancel_next_up_event;//invokes the dispatchtouchevent of a child view, if the child view Dispatchtouchevent returns True, it means that the event//has been consumed by this sub-view and will not continue to pass if (child.dispatchtouchevent (EV)) { Event handled, we have a target now. Mmotiontarget = child; return true; }//The event didn ' t get handled, try the next view. Don ' t reset the event ' s location, it's not//necessary here. }}}}} Boolean isuporcancel = (action = = Motionevent. ACTION_UP) | | (action = = Motionevent.action_cancel); if (isuporcancel) {//Note, we ' ve already copied the previous state to our local//variable, so th is takes effect on the next event mgroupflags &= ~flag_disallow_intercept; }//The event wasn ' t an Action_down, dispatch it to our target if//we have one. Final View target = mmotiontarget;//for a Action_down event, if you go here and show that all sub-View does not consume this event, then it calls the parent class// Dispatchtouchevnet method, the parent class of ViewGroup is the view if (target = = null) {//We have a target, this means we ' Re handling the//event as a regular view. Ev.setlocation (XF, YF); if ((Mprivateflags & cancel_next_up_event)! = 0) {ev.setaction (motionevent.action_cancel); Mprivateflags &= ~cancel_next_up_event; } return super.dispatchtouchevent (EV); }//If has a target, see if we ' re alLowed to and want to intercept it/events if (!disallowintercept && onintercepttouchevent (EV)) { Final Float XC = scrolledxfloat-(float) target.mleft; Final float YC = scrolledyfloat-(float) target.mtop; Mprivateflags &= ~cancel_next_up_event; Ev.setaction (Motionevent.action_cancel); Ev.setlocation (XC, YC); if (!target.dispatchtouchevent (EV)) {//target didn ' t handle action_cancel. Not much we can do But they should has. }//Clear the target mmotiontarget = null; Don ' t dispatch this event to our own view, because we already//saw it when intercepting; We just want to give the following//event to the normal ontouchevent (). return true; } if (isuporcancel) {mmotiontarget = null; }//finally offset the event to the target ' s coordinate System and//dispatch the event. Final Float XC = scrolledxfloat-(float) target.mleft; Final float YC = scrolledyfloat-(float) target.mtop; Ev.setlocation (XC, YC); if ((Target.mprivateflags & cancel_next_up_event)! = 0) {ev.setaction (motionevent.action_cancel); Target.mprivateflags &= ~cancel_next_up_event; Mmotiontarget = null; } return target.dispatchtouchevent (EV); }
just looked at ViewGroup's Dispatchtouchevent method, we saw a method Onintercepttouchevent, this method is what to do, we first see what he has done
public boolean onintercepttouchevent (motionevent ev) { return false; }
Found inside is returned a false, by means of the name we can know the function of the method, whether to prevent the delivery of touchevent, the default is False is not blocked.
Now summarize the logic of ViewGroup's dispatchtouchevnet, after all, this method is somewhat complex:
1. If disallowintercept| | ! Onintercepttouchevent (), then the event can continue to pass, or directly call the ViewGroup's parent class dispatchtouchevent, which is the dispatchtouchevent of the view.
2. Loop through all the child view of the ViewGroup, passing the event to the child view, if a child view has processed the event, and returns True, the event ends, stops passing
3 . If all sub-view does not consume this event, then call the view's dispatchtouchevent
For any Android app, showing the user the top is usually a view, such as Button,imageview and so on, which means that some touch events are eventually passed to the control, if the control consumes these events, then stop passing, if not consumption, So let's take a look at the Dispatchtouchevent method of the ViewGroup that the control belongs to ontouchevnet processing.
public boolean dispatchtouchevent (Motionevent event) { if (montouchlistener! = null && (Mviewflags & Enab Led_mask) = = ENABLED && montouchlistener.ontouch (this, event)) { return true; } Return Ontouchevent (event); }
This method of view is very simple, first to determine whether Mtouchlistener is empty, and whether the view is eneable, if all is satisfied, So first call the Montouchlistener.ontouch method, if the Ontouch method returns True, then that is, this view consumes the event, directly returns True, if Ontouch returns False, Then the Ontouchevnet method is called, what is this montouchlistener?
public void Setontouchlistener (Ontouchlistener l) { montouchlistener = l; }
See this to understand, is that we are assigned by Setontouchlistener, in addition we need to note that this ontouch is executed before the Ontouchevent method Oh.
Finally, let's take a look at the ontouchevnet of the view .
public boolean ontouchevent (Motionevent event) {final int viewflags = mviewflags;//(A) if (ViewFlags & Enabled_mask) = = DISABLED) {//A DISABLED view is clickable still consumes the touch//Event s, it just doesn ' t respond to them. Return (((viewflags & clickable) = = Clickable | | (ViewFlags & long_clickable) = = long_clickable)); if (mtouchdelegate! = null) {if (Mtouchdelegate.ontouchevent (event)) {return true; }}//(B) if (((viewflags & clickable) = = Clickable | | (ViewFlags & long_clickable) = = long_clickable) {switch (event.getaction ()) {case Motione Vent. Action_up:boolean prepressed = (mprivateflags & prepressed)! = 0; if ((Mprivateflags & PRESSED)! = 0 | | prepressed) {//Take focus if we don ' t has it already and we should in//touch mode. Boolean focustaken = false; if (isfocusable () && isfocusableintouchmode () &&!isfocused ()) {Focustaken = R Equestfocus (); if (!mhasperformedlongpress) {//This was a tap, so remove the Longpre SS Check Removelongpresscallback (); Only perform take click Actions if we were in the pressed state if (!focustaken) { Use a Runnable and post this rather than calling//PerformClick D irectly. This lets other visual state//of the view update before click Actions Start. if (Mperformclick = = null) {Mperformclick = new PerformClick (); }//(C) if (!post (Mperformclick)) { PerformClick (); }}} if (munsetpressedstate = = null) { Munsetpressedstate = new Unsetpressedstate (); } if (prepressed) {mprivateflags |= PRESSED; Refreshdrawablestate (); Postdelayed (Munsetpressedstate, Viewconfiguration.getpressedstateduration ()); } else if (!post (munsetpressedstate)) {//If the post failed, unpress right now Munsetpressedstate.run (); } removetapcallback (); } break; Case Motionevent. Action_down:if (Mpendingcheckfortap = = null) {Mpendingcheckfortap = new CHECKF Ortap (); } mprivateflags |= prepressed; Mhasperformedlongpress = false; Postdelayed (Mpendingcheckfortap, Viewconfiguration.gettaptimeout ()); Break Case MotionEvent.ACTION_CANCEL:mPrivateFlags &= ~pressed; Refreshdrawablestate (); Removetapcallback (); Break case MotionEvent.ACTION_MOVE:final int x = (int) event.getx (); Final int y = (int) event.gety (); Be lenient about moving outside of buttons int slop = Mtouchslop; if ((x < 0-slop) | | (x >= getwidth () + slop) | | (Y < 0-slop) | | (Y >= getheight () + slop)) { Outside button Removetapcallback (); if ((Mprivateflags & PRESSED)! = 0) {//Remove any future long Press/tap checks Removelongpresscallback (); Need to switch from pressed to not pressed mprivateflags &= ~pressed; Refreshdrawablestate (); }} break; }//(D) return true; } return false; }
This method is also quite complicated, but we don't have to look at every line, we just have to pick the key to see OK.
Please take a closer look at the four places I marked a B C D, at a where if the view is disable, then as long as the view is clickable or longclickable, then this event is consumed by the view and returns True
Looking at B and D, two places, if the view is clickable or longclickable, then D always returns True, that is, the event has been consumed, as for the c I am mainly stating that the view onclick event is triggered in the action_up.
To learn here, I need to summarize:
If a view that we touch is clickable or longclickable, then this event will certainly be consumed by this view (if you have not rewritten the Onintercepttouchevent method where it is ViewGroup, If you override this method to return true, then view is unable to receive this event)
Now we have to think about a question, if this view does not consume the event, where does the event end up?
Remember the Dispatchtouchevent method that I said earlier about ViewGroup, if all its sub-view does not handle the event, then the Dispatchtouchevnet method of the parent view is called. Thus the Ontouch and Ontouchevent methods of the ViewGroup are implemented.
So if ViewGroup didn't deal with the event, there are two things to be said:
1, if this viewgroup is not decorview, that is to say his father view is a common viewgroup (such as linearlayout inside a linearlayout), So it's a little bit like the above sub-view does not dispose of messages, calling the Ontouch and Ontouchevent methods of the parent class
2, if this viewgroup is Decorview, then call to the activity of the Ontouchevnet method (at this time there is no Ontouch method).
Write it here today, and I'll go back with a simple demo and a simple sliding conflict problem in-depth learning touchevnet events. If there is no clear written, welcome to shoot bricks ...