Android view event mechanism 21 Q 21 Answer

Source: Internet
Author: User

Original:

http://www.cnblogs.com/punkisnotdead/p/5179115.html#3358859

What are the main coordinate parameters of 1.View? What are the main points of attention separately?

A: Left,right,top,bottom Note that these 4 values are actually the relative coordinate values of the view and his parent control. This is not the absolute value from the upper-left corner of the screen.

In addition, X and y are actually coordinate values relative to the parent control. Translationx,translationy these 2 values default to 0, which is the offset from the upper-left corner of the parent control.

Conversion Relationship:

X=left+tranx,y=top+trany.

Many people do not understand why things like this, in fact, if the view has moved, such as panning this, you have to pay attention to, top and left this value will not change.

No matter how you drag the view, the value of the X,y,tranx,trany changes as you drag the pan. Just want to understand this.

When do 2.onTouchEvent and gesturedetector use whichever is better?

A: Only when the demand is sliding with the former, if there is a double-click and other such behavior when the latter.

What problem does 3.Scroller use to solve?

A: View of the Scrollto and Scrollby sliding effect is too poor, is instantaneous completion. The scroller can be combined with the computescroll of the view to achieve the sliding effect of the gradient. Experience better.

What do 4.ScrollTo and Scrollby need to be aware of?

A: The former is absolute sliding, the latter is relative sliding. The content of the view is sliding rather than the view itself. This is important. For example, TextView calls these 2 methods to slide is the content of the displayed word.

Generally speaking, we will use Scrollby more. The value of the words in fact, remember a few laws can be. Right-left X is positive otherwise x is negative on-down Y is negative, otherwise y is positive.

You can take a look at these 2 sources:

1 public void ScrollTo (int x, int y) {2         if (mscrollx! = x | | mscrolly! = y) {3             int oldx = MSCROLLX; 4             int OL DY = mscrolly; 5             mscrollx = x; 6             mscrolly = y; 7             invalidateparentcaches (); 8             onscrollchanged (MSCROLLX, mscrolly, OLDX, OldY); 9             if (!awakenscrollbars ()) {                 postinvalidateonanimation ();             }12         }13     }14  void Scrollby (int x, int y) {         scrollTo (mscrollx + x, mscrolly + y);     

See there are 2 variables mscrollx and mscrolly These 2 things no, the value of these 2 units is pixels, which represents the distance between the left edge of the view and the left edge of the view content. The latter represents the distance between the top edge of the view and the top edge of the view content.

5. What are the consequences of using animations to realize the sliding of a view?

A: Actually, the view animation is the movement of the view's surface UI, which is the visual effect that the user renders, and the animation itself does not move the view's true location. Property animations are excluded. After the animation is finished, the view will eventually

Back to their own position,. Of course, you can set the Fillafter property to allow the view image to remain in place after the animation has finished playing. So this has a very serious consequence. For example, your button is on the left side of the screen,

You now use an animation and set the Fillafter property to let him go to the right. You will find that clicking on the button on the right does not trigger the Click event, but clicking on the left side can be triggered because the button on the right is just the image of the view.

The real button still has no movement on the left. You have to do this. You can put a new button in advance on the right button after the move, when you finish the animation to the right of the left to enable him to gone on it.

Doing so can circumvent these problems.

6. There are several ways to keep the view sliding, what should be noted separately? Apply to those scenes?

A: A total of three kinds:

A:scrollto,scrollby. This is the simplest, but the content of the view can only be slid without sliding the view itself.

B: Animation. Animations can slide the view content, but note that non-attribute animations like what we say in question 5 affect interaction, and pay more attention when using them. However, most of the complex sliding effects are property animations, which belong to the big Kill device level,

C: Change layout parameters. The best way to understand this is to dynamically change the parameters of a view such as margin through Java code. But the use of less. I don't really use this method myself.

What does 7.Scroller do? What is the principle?

A: Scroller is used to let the view have a sliding gradient effect. Use the following:

 1 package com.example.administrator.motioneventtest; 2 3 Import Android.content.Context; 4 Import Android.util.AttributeSet; 5 Import Android.widget.Scroller; 6 Import Android.widget.TextView;  7 8/** 9 * Created by Administrator in 2016/2/2.10 */11 public class Customtextview extends textview{12 Scroller mscroller;14 Public Customtextview (context context) {+ super (context); Mscroller=ne W Scroller (context),}20 public Customtextview (context context, AttributeSet Attrs) (context , attrs), Mscroller=new Scroller (context),}26 public Customtextview (context context, AttributeS ET attrs, int defstyleattr) {(context, attrs, defstyleattr); mscroller=new Scroller (context); 30 31}32 33//Call this method to scroll to the target location of the public void Smoothscrollto (int fx, int fy) {int dx = FX-MSCROLLER.GETF Inalx (); n int dy = fy-mscroller.getfinaly (); Panax Notoginseng smoothsCrollby (dx, dy); 38}39 40//Call this method to set the relative offset of the scroll to the public void Smoothscrollby (int dx, int dy) {42 43//Set MSC Roller rolling offset of mscroller.startscroll (Mscroller.getfinalx (), mscroller.getfinaly (), DX, dy,4000); Ate ();//Must call Invalidate () here to ensure that computescroll () will be called, otherwise it will not necessarily refresh the interface, do not see the scrolling effect 46}47 48//Use Scroller most important do not omit this method @Overr Ide50 public void Computescroll () {Wuyi if (Mscroller.computescrolloffset ())), * ScrollTo ( Mscroller.getcurrx (), Mscroller.getcurry ()); 54//This method do not forget to call. Postinvalidate ();}57 Super.computescroll (); 58}59}

In fact, many of the above code should be able to search. Let's talk about his theory here.

  1//Parameter very good understanding front sliding start point middle sliding distance the last one is the gradient time 2//And we see Startscroll This method is set a parameter and there is no sliding code in 3//back to the previous demo can see we usually call this method after the horse Invalidate () Method 4 public void Startscroll (int startX, int starty, int dx, int dy, int duration) {5 Mmode = S  Croll_mode;  6 mfinished = false;  7 mduration = Duration;  8 mstarttime = Animationutils.currentanimationtimemillis (); 9 Mstartx = StartX; Ten mstarty = Starty; One mfinalx = StartX + dx; Mfinaly = Starty + dy; Mdeltax = DX; Mdeltay = dy; Mdurationreciprocal = 1.0f/(float) mduration; 16} 17 18 19//We all know that invalidate will trigger the view's Draw method 20//We'll follow up to see that the following code is called in the Draw method: 21//means that the Computescroll method is called and V Iew itself this method 22//Is empty so it will be left to us to achieve the 0. the int sy = 0;  if (!drawingwithrendernode) {computescroll (); sx = MSCROLLX; sy = mscrolly; 29} 30 31 32//Then back to our customtextview to see me.The Computescroll methods are as follows: 33//You see in this method we call the Scrollto method to implement the swipe, the swipe ends again to trigger the view redraw 34//And then again trigger the Computescroll to implement a loop. public void Computescroll () {mscroller.computescrolloffset ()) PNs {scrollTo (MSCR Oller.getcurrx (), Mscroller.getcurry ()); 39//This method do not forget to call. Postinvalidate (); Super.computescroll (); 43} 44 45 46//Returns TRUE to indicate that the swipe has not ended false is the end of 47//In fact, this method is the same as the interpolation in the property animation you can use the Startscroll method when the value of an event is passed, 48//This method is based on this The value of the event to calculate the value of your scrollx and scrolly each time, the public boolean Computescrolloffset () {(mfinished) { Alse; timepassed int = (int) (Animationutils.currentanimationtimemillis ()-mstarttime);                 if (timepassed < mduration) {$ switch (mmode) {$ case scroll_mode:59 Final float x = minterpolator.getinterpolation (timepassed * mdurationreciprocal); Mcurrx = Mstartx + Math.Round (x * mdeltax); Mcurry = Mstarty + math.round (x * mdeltay); a break; fling_mode:64 Final Float t = (float) timepassed/mduration; The final int index = (int) (Nb_samples * t); Distancecoef float = 1.f; Velocitycoef float = 0.f;                     if (Index < nb_samples) {final float T_inf = (float) index/nb_samples; 70 Final float T_sup = (float) (index + 1)/nb_samples; Final float d_inf = Spline_position[index]; Final float D_sup = spline_position[index + 1]; Velocitycoef = (d_sup-d_inf)/(T_sup-t_inf); Distancecoef = D_inf + (t-t_inf) * VELOCITYCOEF; mcurrvelocity = Velocitycoef * mdistance/mduration * 1000.0f; McurrX = Mstartx + Math.Round (DISTANCECOEF * (MFINALX-MSTARTX)); //Pin to Mminx <= mcurrx <= mmaxx Bayi Mcurrx = Math.min (Mcurrx, Mmaxx); Mcurrx = Math.max (Mcurrx, Mminx); Mcurry = Mstarty + Math.Round (DISTANCECOEF * (Mfinaly-mstarty)); //Pin to Mminy <= mcurry <= mmaxy * mcurry = Math.min (Mcurry, Mmaxy); Mcurry = Math.max (Mcurry, Mminy);                 if (Mcurrx = = Mfinalx && Mcurry = = mfinaly) {mfinished = true; 91 };             94} (Mcurrx = mfinalx; 98 Mcurry = mfinaly; 99      mfinished = true;100}101 return true;102}103

There are several ways to move a 8.view sliding gradient?

A: Three kinds, the first one is Scroller is also the most used. There is an explanation in question 7. There is also a kind of animation, animation I will not say, not belong to the scope of this article. The last one we often use is to update the state of the view with handler, every other time interval.

The code is not written very simple. Self-experience.

How does the 9.view event passing mechanism be represented by pseudo-code?

For:

1/** 2      * For a root viewgroup, if a click event is accepted, his dispatchtouchevent method is called first. 3      * If this viewgroup onintercepttouchevent returns True, it means to intercept the event. The next event will be 4      * to viewgroup itself, so that the ViewGroup Ontouchevent method will be called. If this viewgroup onintercepttouchevent 5      * Returns false means I do not intercept this event and then pass this event to its own child element, then the child element of the Dispatchtouchevent 6      * will be called, that is, a loop until the event is processed. 7      * 8 *      /9 public boolean dispatchtouchevent (Motionevent ev) {One     -to-one Boolean consume=false;12     if ( Onintercepttouchevent (EV)) {         consume=ontouchevent (EV),     }else15     {         consume= Child.dispatchtouchevent (EV);     }18     return consume;19}

What is the priority of the Ontouch method for the Ontouchevent,onclicklisterner and Ontouchlistener of 10.view?

A: The Ontouchlistener has the highest priority, and if the Ontouch method returns False, the ontouchevent is called and returns true without being called. As for the onclick priority level is lowest.

11. What is the order in which click events are delivered?

Answer: Activity-window-view. pass from top to bottom, of course, if your lowest view ontouchevent returns false that means he doesn't want to handle it, and then he throws it up and doesn't deal with it.

Eventually, the activity was left to deal with itself. For example, PM issued a task to leader,leader himself not to architect A, small a also do not give programmer b,b if done that will end this task.

b If you find that you can not make it, then find a to do, a if you can not do it will continue to initiate the request, and ultimately may be PM.

The Dispatchtouchevent method of the 
 1 2//activity is initially given to the window to process the 3//win superdispatchtouchevent return True and the function is terminated directly. A return of false means 4//This event is not handled, and ultimately to the activity of the ontouchevent themselves to handle the getwindow here is actually Phonewindow 5 public boolean dispatchtouchevent (Motionevent ev) {6 if (ev.getaction () = = Motionevent.action_down) {7 onuserinteraction (); 8} 9 if (     GetWindow (). superdispatchtouchevent (EV)) {Ten return true;11}12 return ontouchevent (EV); 13 }14 15 16///See this function of Phonewindow to pass the event directly to MDecor17 @Override19 public boolean superdispatchtouchevent (Motionevent E Vent) {return mdecor.superdispatchtouchevent (event),}22//devorview is our rootview, that's the framelayout we         The Setcontentview inside the Layout24//Is this Decorview's child view @Override26 public final View Getdecorview () {27 if (Mdecor = = null) {Installdecor ();}30 return mdecor;31} 

12. How many steps does the event take?

A: The down event begins with the end of the up event, and there may be an indefinite number of move events in the middle.

13.ViewGroup How to distribute click events?

For:

 1 ViewGroup is the process of actionmasked = = Motionevent.action_down and Mfirsttouchtarget! = NULL in both cases to determine whether or not to enter the interception event 2 3 see the code to know if it is AC Tion_down event that's going to go into the process of whether to intercept the event 4 5 if it's not the Action_down event, then look at mfirsttouchtarget! = NULL if this condition is set up 6 7 This place is a little bit around but understanding, is actually for a thing The sequence is the beginning of the event so it must have entered the event whether the interception process is within the IF bracket. 8 9 Mfirsttouchtarget is actually a single-linked list structure. He points to a child element that successfully handles an event. 11 12 That is, if there are child elements that successfully handle the event, the value is not NULL. On the other hand 13 14 only ViewGroup intercept the event, Mfirsttouchtarget is not null, so the parentheses will not be executed, but also on the side of a conclusion: 15 16 When a view decides to intercept an event, the event sequence that the event belongs to Can only be carried out by him. And onintercepttouchevent This method will not be called by the final Boolean intercepted;19 if (actionmasked = = Motioneve Nt. Action_down20 | | Mfirsttouchtarget = null) {Final Boolean disallowintercept = (Mgroupflags & FLAG_DISALLOW_INTERCEP                     T)! = 0;22 if (!disallowintercept) {intercepted = Onintercepttouchevent (EV); 24 Ev.setaction (action);             Restore action in case it was changed25    } else {intercepted = False;27}28} else {//Th Ere is no touch targets and this action is not a initial down30//So the view group continues to inter Cept touches.31 intercepted = true;32}

14. What happens if a view processing event does not consume the down event?

A: If a view, at the time of the down event, his ontouchevent returns false, then the sequence of events to which the down event belongs is his subsequent move and up will not be dealt to him, all to his father view processing.

15. What happens if the view does not consume move or up events?

A: The sequence of events that this event belongs to disappears, and the parent view does not handle it, and eventually it is addressed to the activity.

16.ViewGroup Default intercept event?

A: The default does not intercept any events, Onintercepttouchevent returns false.

17. Once an event is passed to View,view, will the ontouchevent be called?

A: Yes, because the view itself does not have a onintercepttouchevent method, so as long as the event comes to view here will certainly go ontouchevent method.

And by default it is consumed and returns true. Unless the view is not clickable, the so-called non-clickable is clickable and longgclikable simultaneously for Fale

The clickable of the button is true but TextView is false.

Does 18.enable affect the Ontouchevent return value of the view?

Answer: No, as long as clickable and longclickable have a true, then Ontouchevent returns True.

19.requestDisallowInterceptTouchEvent can you interfere with the event distribution of parent elements in child elements? If so, can all be interfered with?

A: Sure, but the down event will not interfere.

20.dispatchTouchEvent will be called every time?

A: Yes, onintercepttouchevent is not.

21. What is the solution to the problem of sliding conflict?

For. To solve the sliding conflict, the main thing is to have a core idea. In which view do you want to respond to your swipe in a sequence of events? For example, from top to bottom, which view to handle this event, from left to right?

Use business needs to understand that the rest of the matter is really good to do. The core method is the 2 external interception is the Father intercept, and the other is the internal interception, that is, sub-view interception method. Learn these 2 kinds of basically all the sliding conflicts

Are all of these 2 variants, and the core code ideas are the same.

External interception method: The idea is to rewrite the parent container's onintercepttouchevent. Child elements generally do not require a tube. It's easy to understand because it's exactly the same logic as the Android's own event-handling mechanism.

Android view event mechanism 21 Q 21 Answer

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.