Android view event Mechanism 21 Ask 21 answer _android

Source: Internet
Author: User
Tags gety

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

A: Left,right,top,bottom Note that these 4 values are actually the relative coordinates of the view and his parent control. It is not the absolute value of the upper-left corner of the screen, this should be noted.

In addition, X and Y are in fact relative to the parent control's coordinate values. Translationx,translationy these 2 values default to 0, which is the offset relative to 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 there is a move, such as translation of this, you should 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 varies with the drag translation. Just want to understand this.

2.onTouchEvent and Gesturedetector when to use which is better?

A: Only when the need to slide the use of the former, if there is a double-click such behavior when the latter.

3.Scroller to solve what problem?

A: View of the Scrollto and Scrollby sliding effect is too bad, is instantaneous completion. The scroller can be combined with the view Computescroll to complete 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 and the latter is relative sliding. The slide is the content of the view rather than the view itself. This is important. For example, the 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 on it. Right-left X is positive otherwise x is negative-lower y is negative, otherwise y is positive.

Can take a look at these 2 source code:

public void Scrollto (int x, int y) {
if (mscrollx!= x | | mscrolly!= y) {
int oldx = MSCROLLX;
int oldy = mscrolly;
MSCROLLX = x;
mscrolly = y;
Invalidateparentcaches ();
Onscrollchanged (MSCROLLX, mscrolly, OLDX, oldy);
if (!awakenscrollbars ()) {
postinvalidateonanimation ();
}}} public void Scrollby (int x, int y) {
Scrollto (mscrollx + x, mscrolly + y);
}

See that there are 2 variables mscrollx and mscrolly These 2 things are not, these 2 units of the value is pixels, the former represents the left edge of view and the distance of 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 achieve view sliding?

A: Actually, the view animation is a move to the view's surface UI, which is the visual effect of the user, and the animation itself does not move the view's real position. Except for property animations. After the animation is finished, the view will eventually return to its own position. Of course, you can set the Fillafter property to allow the view representation to stay in place after the animation is finished. 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 trigger, because the button on the right is just the appearance of the view, and the real button is not moving on the left. You have to do this. You can put a new button in the position of the right button before moving it, and when you finish the animation, put the left side to the right to let him gone.

This can be done to circumvent these problems.

6. Let the view slide there are several ways to pay attention to what? Apply to those scenes?

A total of three:

A:scrollto,scrollby. This is the simplest, but only sliding view content can not slide the view itself.

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

C: Change the layout parameters. This is best understood, nothing more than dynamic through the Java code to modify the margin and other view parameters. But the use is relatively few. I don't use this method personally.

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

A: Scroller is used to let view have sliding gradient effect. Usage is as follows:

Package com.example.administrator.motioneventtest;
Import Android.content.Context;
Import Android.util.AttributeSet;
Import Android.widget.Scroller;
Import Android.widget.TextView;
/** * Created by the Administrator on//.

* * public class Customtextview extends textview{private scroller Mscroller; Public Customtextview {Super (context), mscroller=new scroller (context), Public customtextview ( Context context, AttributeSet Attrs) {Super (context, attrs); mscroller=new scroller (context);} public Customtextview (Co ntext context, AttributeSet attrs, int defstyleattr) {Super (context, attrs, defstyleattr); Mscroller=new scroller (Contex
T); //Call this method to scroll to the target location public void Smoothscrollto (int fx, int fy) {int dx = FX-MSCROLLER.GETFINALX (); int dy = Fy-mscroller
. Getfinaly ();
Smoothscrollby (dx, dy); //Call this method to set the relative offset of scrolling public void Smoothscrollby (int dx, int dy) {//Set Mscroller's scrolling offset mscroller.startscroll (
Mscroller.getfinalx (), mscroller.getfinaly (), DX, DY,); Invalidate ()//Must be tuned here.Use invalidate () to ensure that computescroll () will be invoked, otherwise it will not necessarily refresh the interface, do not see the scrolling effect}//Use Scroller most important do not omit this method @Override public void Computescroll () {if (Mscroller.computescrolloffset ()) {Scrollto (Mscroller.getcurrx (), Mscroller.getcurry ());
This method does not forget to call.
Postinvalidate ();
} super.computescroll (); }
}

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

The parameters are well understood. The last one is the gradient time//And we see startscroll this method is to set the parameters and there is no sliding code in//back to the previous demo can see we usually call the end of this method after
Will immediately invoke the invalidate () method public void Startscroll (int startx, int starty, int dx, int dy, int duration) {mmode = Scroll_mode;
Mfinished = false;
mduration = Duration;
Mstarttime = Animationutils.currentanimationtimemillis ();
Mstartx = StartX;
Mstarty = Starty;
MFINALX = startx + dx;
Mfinaly = Starty + dy;
Mdeltax = DX;
Mdeltay = dy;
Mdurationreciprocal =. F/(float) mduration; 
//We all know that invalidate triggers the view's Draw method//We follow up and see that the following code is called in the Draw method://That is, the Computescroll method is called and the view itself is empty so it will be left to us.
int SX =;
int sy =; if (!drawingwithrendernode) {computescroll (); sx = mscrollx; sy = mscrolly;}//Then go back to our customtextview and see what we've achieved Computesc
The roll method is as follows://You see in this method we call the Scrollto method to implement the slide, and then trigger the view redraw again after the slide is over and then trigger the Computescroll to implement a loop again. public void Computescroll () {if (Mscroller.computescrolloffset ()) {Scrollto (), Mscroller.getcurrx (), Mscroller.getcurry
());
This method does not forget to call.
Postinvalidate ();} super.computescroll (); //Returns True to mean that the slide is not over, false is ending//In fact, this method is the same as the interpolation in the attribute animation. You will pass the value of an event when you use the Startscroll method. This method calculates the value of each SCROLLX and scrolly based on the value of this event public boolean computescrolloffset () {if (mfinished) {return false;} int Timepas
sed = (int) (Animationutils.currentanimationtimemillis ()-mstarttime); if (timepassed < mduration) {switch (mmode) {case scroll_mode:final float x = minterpolator.getinterpolation (Timepas
SED * mdurationreciprocal);
Mcurrx = Mstartx + math.round (x * mdeltax);
Mcurry = Mstarty + math.round (x * mdeltay);
Break
Case fling_mode:final Float t = (float) timepassed/mduration;
Final int index = (int) (Nb_samples * t);
float Distancecoef =. F;
float Velocitycoef =. F; if (Index < nb_samples) {final float T_inf = (float) index/nb_samples; final float t_sup = (float) (index +)/nb_s
Amples;
Final float d_inf = Spline_position[index];
Final float D_sup = Spline_position[index +];
Velocitycoef = (d_sup-d_inf)/(T_sup-t_inf); Distancecoef = D_inf+ (t-t_inf) * VELOCITYCOEF;
} mcurrvelocity = Velocitycoef * mdistance/mduration *. f;
Mcurrx = Mstartx + Math.Round (DISTANCECOEF * (MFINALX-MSTARTX));
Pin to Mminx <= mcurrx <= Mmaxx 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;} break;
} else {mcurrx = mfinalx; mcurry = mfinaly; mfinished = true;} return true; }

How many methods are there in the 8.view sliding gradient effect?

Answer: Three kinds, the first one is Scroller is also used most. There are explanations in question 7. There is another kind of animation, animation I do not say more, does not belong to the scope of this article. The last one we often use is to update the view state at intervals of handler.

The code is not written very simply. Own experience.

How can the 9.view event-passing mechanism be represented in pseudocode?

For:

/**
* For a root viewgroup, if a click event is accepted, his Dispatchtouchevent method is first invoked.
* If this viewgroup onintercepttouchevent returns True, it means to intercept the event. The next event will be
addressed to ViewGroup itself, so that the ViewGroup Ontouchevent method is invoked. If this viewgroup onintercepttouchevent
* Returns false it means I don't intercept the event, and then I pass this event to my own child element, and then the child element's Dispatchtouchevent
* is called, which is the loop until the event is processed.
*
*
/public boolean dispatchtouchevent (motionevent ev)
{
Boolean consume=false;
if (onintercepttouchevent (EV)) {
consume=ontouchevent (EV);
} else
{
consume=child.dispatchtouchevent (EV);
}
return consume;

10.view Ontouchevent,onclicklisterner and Ontouchlistener Ontouch method of the three priority?

A: Ontouchlistener is the highest priority, if the Ontouch method returns False, the ontouchevent is invoked, and return true will not be invoked. As for the onclick priority is the lowest.

11. What is the order of delivery of the click events?

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

Eventually let the activity handle itself. For example, PM issued a task to leader,leader himself do not give architect A, small a also do not do to programmers b,b if done that will end the task.

b If you find that you can not, then find a to do, a if you can not do it will continue to initiate requests, may eventually be PM.

The Dispatchtouchevent method of the activity begins with the window to deal with the
//win Superdispatchtouchevent returns true that ends the function directly. return false means
//This incident is not handled, and ultimately to the activity of the ontouchevent to deal with themselves here GetWindow is actually Phonewindow public
Boolean Dispatchtouchevent (motionevent ev) {
if (ev.getaction () = = Motionevent.action_down) {
onuserinteraction ();
}
if (GetWindow (). superdispatchtouchevent (EV)) {return
true;
}
return ontouchevent (EV);
}
This function to see Phonewindow directly passes the event to the Mdecor
@Override public
boolean superdispatchtouchevent (Motionevent event) {return
mdecor.superdispatchtouchevent (event);
}
Devorview is our Rootview, the layout that framelayout our Setcontentview, that's the Decorview
's son view.
Override public
final View Getdecorview () {
if (Mdecor = null) {
Installdecor ();
}
return Mdecor;
}

12. How can the incident be divided into several steps?

A: The beginning of the down event, the end of the up event, may have an indefinite number of move events in between.

13.ViewGroup How do I distribute the click events?

For:

ViewGroup is the actionmasked = = Motionevent.action_down and mfirsttouchtarget!= Null in both cases to determine whether the process of intercepting the event to see the code can know if it is action_ Down event that would definitely go into whether to intercept the process of an event if it's not a Action_down event, it depends on whether the condition of Mfirsttouchtarget!= NULL is set up. This place is a bit around but understanding, in fact, is for a sequence of events Down is the beginning of the event so it must have entered the process of whether or not the event was intercepted.
Mfirsttouchtarget is actually a single linked list structure he points to the child elements that successfully handle the event.
That is, if a child element succeeds in handling the event, the value is not NULL. Conversely, as long as the ViewGroup intercepts the event, the mfirsttouchtarget is not NULL, so it is not executed in parentheses, and a conclusion is also presented on the side:

Once a view decides to intercept an event, the sequence of events that the event belongs to can only be performed by him. And onintercepttouchevent This method will not be invoked.

Final Boolean intercepted;
if (actionmasked = = Motionevent.action_down
| | | mfirsttouchtarget!= NULL) {
final Boolean disallowintercept = (MG Roupflags & Flag_disallow_intercept)!=;
if (!disallowintercept) {
intercepted = onintercepttouchevent (EV);
Ev.setaction (action); Restore action in case it is changed
} else {
intercepted = false;
}
} else {
//There are no to Uch targets and this action are not a initial down
//So this view group continues to intercept touches.
intercepted = true;

14.: What will be the result of a view that does not consume down events when handling events?

A: If a view, when the down event comes, his ontouchevent returns false, then the sequence of events that the down event belongs to is that his subsequent move and up will not be dealt with by him, all to his parent view.

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 will not be dealt with, and eventually it will be dealt with by the activity.

16.ViewGroup The default interception event?

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

17. Will ontouchevent be called once an event is passed to View,view?

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

And the default is to consume and return true. Unless this view is not clickable, the so-called clickable is clickable and longgclikable at the same time Fale

The button's clickable is true but TextView is false.

Does 18.enable affect view's ontouchevent return value?

A: It does not affect, as long as clickable and longclickable have one true, then Ontouchevent returns True.

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

A: Sure, but the down event won't interfere.

20.dispatchTouchEvent will be called every time?

A: Yes, onintercepttouchevent is not.

21. How does the problem of sliding conflict solve the idea?

For. The most important thing in solving sliding conflicts is to have a core idea. What do you want to do in a sequence of events, which view responds to your slide? For example, from top to bottom, which view is to handle this event, from left to right?

Use the business needs to understand that the rest is actually very good to do. The core of the method is 2 external interception is the Father intercept, in addition to the internal interception, that is, the child view interception method. Learn these 2 kinds of basically all sliding conflicts are variants of these 2 kinds, and the core code is the same idea.

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

@Override Public
Boolean onintercepttouchevent (motionevent ev) {
Boolean intercepted = false;
int x = (int) ev.getx ();
int y = (int) ev.gety ();
Switch (ev.getaction ()) {
//down event must not intercept the back will not receive the case
Motionevent.action_down:
intercepted = false;
break;
Case Motionevent.action_move:
if (your business needs) {
//If the interception is determined to go to their own ontouchevent to deal with interception after the operation and effect can be
intercepted = true;
} else {
intercepted = false;
}
break;
Case MOTIONEVENT.ACTION_UP:
//up event We generally return false to the normal parent container will not intercept him. Because up is the last step of the event. It doesn't make sense to return true here
./The only meaning is because the parent element up is blocked. Causes the child element not to receive the up event, that child element certainly does not have the OnClick event to trigger, here the
//small detail wants to understand
intercepted = false;
break;
Default: Break
;
}
return intercepted;

Internal interception method: The internal interception method is slightly more complex, is when the event arrives, the parent container regardless, lets the child element oneself decide whether to handle. If the consumption of the best, no use of natural transfer to the parent container processing.

Child Element Code:

@Override Public
Boolean dispatchtouchevent (Motionevent event) {
int x = (int) event.getx ();
int y = (int) event.gety ();
Switch (event.getaction ()) {case
Motionevent.action_down:
getparent (). requestdisallowintercepttouchevent (true);
break;
Case Motionevent.action_move:
if (if the parent container needs this click event) {
getparent (). Requestdisallowintercepttouchevent (False) ;
} Otherwise, you give yourself the view of the ontouchevent automatically handle the break
;
Case MOTIONEVENT.ACTION_UP: Break
;
Default: Break
;
}
Return Super.dispatchtouchevent (event);

The Father container Code also wants to revise, actually is guarantees the father does not intercept down:

@Override Public
Boolean onintercepttouchevent (motionevent ev) {
if ev.getaction () = = Motionevent.action_ Down) {return
false;
}
return true;
}
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.