Code commentary Android Scroller, Velocitytracker

Source: Internet
Author: User

The android touch mechanism and scroller and velocitytracker are often used when writing your own definition of sliding controls. Android Touch System Brief Introduction (II): instance specific explanation Onintercepttouchevent and Ontouchevent call process A specific explanation is given to the functions that the Android touch mechanism needs to use. This paper mainly introduces two important classes: Scroller and Velocitytracker. Using the above knowledge, a demo that defines the sliding control is given, which is similar to Imagegallery.

The imagegallery is usually implemented with the GridView and can slide left and right. This example implements a control that inherits directly from a viewgroup, overloading its callback functions such as Ontouchevent, Onintercepttouchevent, Computescroll, and so on. Understand the code. The understanding of Android touch will be a deeper layer.

Velocitytracker: For speed tracking of touch points, easy to get touch point speed.
How to use: it is generally called in the Ontouchevent event. Get a Vecolitytracker object in the down event first, and then get the speed in the move or up event, which can be seen for example in the following:

Velocitytracker vtracker = null; @Override public  boolean ontouchevent (Motionevent event) {  int action = Event.getaction ();  Switch (action) {case  Motionevent.action_down:  if (vtracker = = null) {  vtracker = Velocitytracker.obtain () ;  } else{  vtracker.clear ();  }  Vtracker.addmovement (event);  break;  Case Motionevent.action_move:  vtracker.addmovement (event);  Sets the unit, 1000 indicates how many pixels per second (pix/second), and 1 represents how many pixels per microsecond (pix/millisecond). Vtracker.computecurrentvelocity (+);  A positive number is returned from left to right, and a negative number is returned from right to left System.out.println ("The x Velocity is" +vtracker.getxvelocity ());  A positive number is returned from the top, and a negative number is returned from the bottom up System.out.println ("The Y Velocity is" +vtracker.getyvelocity ());  break;  Case MOTIONEVENT.ACTION_UP: Case  motionevent.action_cancel:  vtracker.recycle ();  break;  }  return true;  }  


Scroller: Tracks that are used to track control slippage. This class does not move the control and requires you to control a view by using the Scroller object in the view's callback function, Computerscroll (), and getting the sliding data.

  /** * Called by a, parent to request, a child update its values for MSCROLLX * and mscrolly if necessary. This would typically be do if the child is * animating a scroll using a {@link Android.widget.Scroller Scroller} * Object . */public void Computescroll () {}
Parentview in the drawing type. Will call Dispatchdraw (canvas canvas), which invokes the Boolean draw for each child view in ViewGroup (Canvas canvas, viewgroup parent, long Drawingtime), the user draws the view, which calls Computescroll () during the drawing of the view
Here's a piece of code:
@Overridepublic void Computescroll () {//TODO auto-generated method STUBLOG.E (TAG, "Computescroll"); Mscroller.computescrolloffset ()) {//or!mscroller.isfinished () log.e (TAG, Mscroller.getcurrx () + "======" + Mscroller.getcurry ()); ScrollTo (Mscroller.getcurrx (), Mscroller.getcurry ()); LOG.E (TAG, "# # GetLeft is" + getleft () + "# # GetRight is" + getRight ());p ostinvalidate (); ELSELOG.I (TAG, "has done the scoller-----");}
This code calls Mscroller.computescrolloffset () before sliding the view to infer whether the slide animation has ended. The source code for Computerscrolleroffset () is as follows:

/** * Call this is the new location of want to know. If it returns True, * The animation is not yet finished. */Public Boolean computescrolloffset () {if (mfinished) {return false;} The slide has been continuous for the time int timepassed = (int) (Animationutils.currentanimationtimemillis ()-mstarttime);//If it is not exhausted at the specified time, Then continue to set the new sliding position Mcurrx and Mcurryif (timepassed < mduration) {switch (mmode) {case Scroll_mode:float x = timepassed * MDURATIONR Eciprocal;if (Minterpolator = = null) x = Viscousfluid (x); Elsex = minterpolator.getinterpolation (x); Mcurrx = Mstartx + math.round (x * mdeltax); Mcurry = Mstarty + Math.round (x * mDe Ltay); break;case fling_mode:final float t = (float) timepassed/mduration;final int index = (int) (Nb_samples * t); float Distancecoef = 1.f;float Velocitycoef = 0.f;if (Index < nb_samples) {final float T_inf = (float) index/nb_samples;fin Al float T_sup = (float) (index + 1)/nb_samples;final float d_inf = spline_position[index];final float D_sup = Spline_po Sition[index + 1];velocitycoef = (d_sup-d_inf)/(t_sup-t_inf);d Istancecoef = D_inf + (t-t_inf) * VELOCITYCOEF;} mcurrvelocity = Velocitycoef * mdistance/mduration * 1000.0f;mcurrx = mstartx + Math.Round (DISTANCECOEF * (mfinalx-mst ARTX));//Pin to Mminx <= mcurrx <= mmaxxmcurrx = Math.min (Mcurrx, mmaxx); Mcurrx = Math.max (Mcurrx, mMinX); MCurrY =  Mstarty + math.round (DISTANCECOEF * (Mfinaly-mstarty));//Pin to Mminy <= mcurry <= mmaxymcurry = 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;}
Viewgroup.computescroll () Call time:
When we run Ontouch or invalidate () or postinvalidate () will cause this method to run.

When we are developing controls. This is often a requirement: when a button is on a single machine. A picture slides out of the form within a specified period of time. Instead of entering the form all at once. This functionality can be implemented using Scroller.
Here's a piece of code that controls the effect that the next interface slowly enters within 3 seconds.

public void Movetorightside () {if (curscreen <= 0) {return;} curscreen--; LOG.I (TAG, "----movetorightside----curscreen" + curscreen); Mscroller.startscroll ((Curscreen + 1) * getwidth (), 0,-getW Idth (), 0, ScrollTo (Curscreen * getwidth (), 0); invalidate ();}
The code above uses a function: void android.widget.Scroller.startScroll (int startX, int starty, int dx, int dy, int duration)
The Computescrolloffset method always returns True when the Startscroll is running during the duration time, but returns false when the animation finishes running.
The source code for this function, as seen below, is mainly used to set the sliding parameters

/** * Start scrolling by providing a starting point, the distance to travel, * and the Durat Ion of the scroll. * * @param startX starting horizontal scroll offset in pixels. Positive * Numbers would scroll the content to the left. * @param starty starting vertical scroll offset in pixels. Positive numbers * would scroll the content up. * @param dx horizontal distance to travel. Positive numbers would scroll the * content to the left. * @param dy Vertical distance to travel. Positive numbers would scroll the * content up. * @param duration duration of the scroll in milliseconds. */public void Startscroll (int startX, int starty, int dx, int dy, int duration) {Mmode = scroll_mode;mfinished = False;mdu ration = Duration;mstarttime = Animationutils.currentanimationtimemillis (); mstartx = Startx;mstarty = StartY;mFinalX = StartX + dx;mfinaly = starty + dy;mdeltax = Dx;mdeltay = Dy;mdurationreciprocal = 1.0f/(float) mduration;} 
Invalidate () causes the view to redraw, causing the parent to call Dispatchdraw (canvas canvas) and then recursively invoke the draw () function of child view. This function also calls our defined Computescroll (), which in turn calls Mscroller.computescrolloffset () to infer whether the animation is over. If it does not end, the redraw continues until the time set in Startscroll is exhausted Mscroller.computescrolloffset () returns false to stop.

Enclose the full instance code:

Define your own Android sliding control source code execution For example, the slide screen will show different pictures.







Code commentary Android Scroller, Velocitytracker

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.