Android interface sliding implementation --- Scroller class learning from source code and development documentation (let your layout move)

Source: Internet
Author: User

In android learning, Action interaction is an important part of software, and Scroller is a class that provides the drag effect. On the internet, for example, some Launcher screens can be implemented through this class ..
The SlidingLayer, an open-source library for side navigation, is actually implemented using the scroroller class: GITHUB, which is not the Library mentioned below, it is the Scroller class used in the implementation process of this library. After understanding it, you can see the source code of the Library. It was originally implemented in this way.


The following mechanism may be more helpful for the development of Scroller classes:
1. VIEW customization and its layout on the screen.
2. The difference between scrollTo () and scrollBy () methods can be found here: android layout slide to explore the use of scrollTo and scrollBy Methods
3. Touch event distribution mechanism in the screen (this part is important in any situation involving touch)


First, let's take a look at what is said in the Development Documentation: android development documentation
Development document reference link: http://developer.android.com? Http://www.bkjia.com/kf/ware/vc/ "target =" _ blank "class =" keylink "> encrypt + CgoKPGgyPtK7Lr3hubm52M + decrypt + tv4uumxk91_vadi + merge =" t automatically apply those positions to your view. it's your responsibility to get and apply new coordinates at a rate that will make the scrolling animation look smooth.


This class encapsulates rolling operations. You can perform smooth scrolling operations on the Interface Based on your gestures.

To track the changing positions of the x/y coordinates, usecomputeScrollOffset(). The method returns a boolean to indicate whether the scroller is finished. if it isn' t, it means that a fling or programmatic pan operation is still in progress. you can use this method to find the current offsets of the x and y coordinates, for example:


Track the position of the x/y coordinates of a change, and monitor the returned Boolean value through the computescroloffset () method to indicate whether the rolling action is completed. If the returned value is false, the scrolling is complete. Returns true, which means the operation is still in progress. You can use

Int currX = mScroller. getCurrX (); // The X-scroll distance of the scroll.

Int currY = mScroller. getCurrY (); // The y rolling distance

This method is used to find the offset of the current x and y coordinates.


Iii. Constructor
Public Constructors

Scroller (Context context) Create a Scroller with the default duration and interpolator.

Scroller (Context context, Interpolator interpolator) Create a Scroller with the specified interpolator.

Scroller (Context context, Interpolator interpolator, boolean flywheel) Create a Scroller with the specified interpolator.

Interpolator interpolator indicates the animation insertor. You can set the effect for it.


Interpolator

Implements TimeInterpolator

Android. view. animation. Interpolator

Known Indirect Subclasses

Signature, AccelerateInterpolator, AnticipateInterpolator, AnticipateOvershootInterpolator, BounceInterpolator, CycleInterpolator, DecelerateInterpolator, LinearInterpolator, OvershootInterpolator


AccelerateDecelerateInterpolator animation effect: the start and end are both slow, and acceleration is enabled in the middle.

AccelerateInterpolator, animation effect: starts slowly and then accelerates

AnticipateInterpolator, animation effect: start to move back and then forward

AnticipateOvershootInterpolator

BounceInterpolator, animation effect: slowly bounce to the end, elastic attenuation to the end

CycleInterpolator, animation effect: Repeated loop animation, speed changes follow the sine Law

DecelerateInterpolator, animation effect: Starting from fast, then slowing down

LinearInterpolator, animation effect: constant changes

OvershootInterpolator animation effect: goes beyond the final point and returns


You can use the initialization constructor Scroller (Context context, Interpolator interpolator) to give it an animation effect.

Interpolator interpolator = new BounceInterpolator ();


Iv. Public Methods

Public Methods
Void AbortAnimation () stops the animation and rolls to the final position x and y to stop the animation.
Boolean Computescroloffset () This method is called when you want to know the new location. Returns true: the animation has not ended.
Void ExtendDuration (int extend) extends the animation time. Extend indicates the delay time (unit: milliseconds)
Void Fling (int startX, int startY, int velocityX, int velocityY, int minX, int maxX, int minY, int maxY) in fling) starting to scroll Based on the gesture, the rolling distance depends on the initial speed of fling.
Final void ForceFinished (boolean finished) Forcibly terminates the scroll.
Float GetCurrVelocity () returns the current speed
Final int GetCurrX () returns the offset of the X direction of the current scroll (from the X axis of the origin)
Final int GetCurrY () returns the offset of the current scrolling Y direction (from the Y axis of the origin)
Final int GetDuration () returns the duration of the rolling event (MS)
Final int GetFinalX () returns the offset of X to the end of the scroll (Note: only valid for the fling gesture) (from the X axis to the origin)
Final int GetFinalY () returns the offset of the Y direction of the rolling end (Note: only valid for the fling gesture) (from the Y axis of the origin)
Final int GetStartX () returns the X-direction offset of the rolling start point (from the X-axis of the origin)
Final int GetStartY () returns the Y offset from the starting point of the scroll (from the Y axis of the origin)
Final boolean IsFinished () returns whether scroller scrolling ends. true: Rolling ends. false: Still scrolling.
Void SetFinalX (int newX) is used to set the offset in the X direction when scroller is terminated.
Void SetFinalY (int newY) sets the offset of the Y direction at the end of scroller.
Final void SetFriction (float friction) The amount of friction applied to flings.
Void StartScroll (int startX, int startY, int dx, int dy) provides the start point and the scroll distance. You can call this method to scroll. (The default time is 250 ms)
Void StartScroll (int startX, int startY, int dx, int dy, int duration) provides the starting point, the rolling distance, and the rolling time. You can call this method to scroll.
Int TimePassed () returns the time (in milliseconds) from the start of scrolling)


Source code

Let's take a look at the source code implementation of the above method:

Knowledge Point 1: computescroloffset () method

/*** Call this when you want to know the new location. if it returns true, * the animation is not yet finished. loc will be altered to provide the * new location. */public boolean computescroloffset () {if (mFinished) {return false; // if the animation has been completed, return false} int timePassed = (int) (AnimationUtils. currentAnimationTimeMillis ()-mStartTime); if (timePassed <mDuration) {switch (mMode) {case SCROLL_MODE: float x = timePassed * mDurationReciprocal; if (mInterpolator = null) x = viscousFluid (x); else x = mInterpolator. getInterpolation (x); 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 = 1.f; float velocityCoef = 0.f; if (index <NB_SAMPLES) {final float t_inf = (float) index/NB_SAMPLES; 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 mm1_< = mCurrX <= mMaxX mCurrX = Math. min (mCurrX, mMaxX); mCurrX = Math. max (mCurrX, mmry); 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 ;}

Call this method to determine whether the scroll is still in progress. The mFinished attribute determines whether the scroll is complete. If the scroll is complete, mFinished = true, computescroloffset () returns false.


Knowledge Point 2: computeScroll () method

/*** Called by a parent to request that a child update its values for mScrollX * and mScrollY if necessary. this will typically be done if the child is * animating a scroll using a {@ link android. widget. scroller} * object. */The parent view is called to request the child view to re-draw the public void computeScroll () {} Based on the Offset Value of mScrollX (){}

Now that we know whether computescroloffset () is used to determine whether to scroll, we must have monitoring Sliding Screen Control and re-paint. In the VIEW class of the Android framework, computeScroll () is provided () this method controls the process. This method is called during the draw () process when a View is drawn. Therefore, when we use the Scroller instance together, we can obtain the current offset coordinates and manually offset the View/ViewGroup to this place.

Note: offset control is implemented using Scroller. Generally, this method needs to be reloaded for custom views and viewgroups.

Specific implementation:

@ Overridepublic void computeScroll () {if (mScroller. computescroloffset () {scrollTo (mScroller. getCurrX (), mScroller. getCurrY (); // update the interface postInvalidate (); isMoving = true;} else {isMoving = false;} super. computeScroll ();}


Knowledge Point 3: startScroll () method
/*** Start scrolling by providing a starting point and the distance to travel. ** @ param startX // the Offset Value of horizontal scrolling, in pixels. A positive value indicates that the Scroll will scroll to the left * @ param startY // The Offset Value of the vertical scroll, in pixels. A positive value indicates that the Scroll will scroll up * @ param dx // The sliding distance in the horizontal direction. A positive value will scroll to the left * @ param dy // The sliding distance in the vertical direction, A positive value will scroll up * @ param duration // rolling duration */public void startScroll (int startX, int startY, int dx, int dy, int duration) {mMode = SCROLL_MODE; mFinished = false; mDuration = duration; mStartTime = AnimationUtils. round (); mStartX = startX; mStartY = startY; mFinalX = startX + dx; mFinalY = startY + dy; mDeltaX = dx; mDeltaY = dy; mDurationReciprocal = 1.0f/(float) mDuration ;}

This method starts to scroll at the provided starting point and the distance from which to slide. We can use this method to automatically scroll. If any conditions are met in scrolling, you can call this method to scroll it to the corresponding place.


Key points:

In Page scrolling, you must understand the difference between scrollTo and scrollBy: android layout slide exploring the use of scrollTo and scrollBy Methods


It should be noted that when moving, the value is negative, and the value is negative. As follows:


Procedure:

If you use Scroller, the process is as follows:

1. You can initialize the Scroller constructor as needed in the custom layout.

2. Override the onInterceptTouchEvent (MotionEvent ev) method to see if you want to intercept the related Click Time.

3. Override the onTouchEvent (MotionEvent event) method and use computeScroll () and scrollTo and scrollBy methods on the touch screen to slide the Layout Based on the fingers.

4. after the touch operation ends (MotionEvent. when ACTION_UP), call the startScroll (int startX, int startY, int dx, int dy, int duration) method to perform automatic animation operations to complete the entire rolling process.


The general usage and introduction of the scroroller class have been completed, and several nice effects of the class implementation will be put on your own.


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.