Scroller的应用--滑屏实现

来源:互联网 发布:网络写手怎样才有收入 编辑:程序博客网 时间:2024/05/29 17:06

1、Scroller源码分析

下面是对Scroller源码的分析,并附有源码,如下:
[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <span style="font-size:18px;">package android.widget;  
  2.   
  3. import android.content.Context;  
  4. import android.hardware.SensorManager;  
  5. import android.os.Build;  
  6. import android.util.FloatMath;  
  7. import android.view.ViewConfiguration;  
  8. import android.view.animation.AnimationUtils;  
  9. import android.view.animation.Interpolator;  
  10.   
  11.   
  12. /** 
  13.  * 这个类封装了滚动 
  14.  * <p>This class encapsulates scrolling. You can use scrollers ({@link Scroller} 
  15.  * or {@link OverScroller}) to collect the data you need to produce a scrolling 
  16.  * animation—for example, in response to a fling gesture. Scrollers track 
  17.  * scroll offsets for you over time, but they don't automatically apply those 
  18.  * positions to your view. It's your responsibility to get and apply new 
  19.  * coordinates at a rate that will make the scrolling animation look smooth.</p> 
  20.  * 
  21.  * <p>Here is a simple example:</p> 
  22.  * 简单实例 
  23.  * <pre> private Scroller mScroller = new Scroller(context); 
  24.  * ... 
  25.  * public void zoomIn() { 
  26.  *     // Revert(重复) any animation currently in progress 
  27.  *     mScroller.forceFinished(true); 
  28.  *     // Start scrolling by providing a starting point and 
  29.  *     // the distance to travel 
  30.  *     mScroller.startScroll(0, 0, 100, 0); 
  31.  *     // Invalidate to request a redraw 
  32.  *     invalidate(); 
  33.  * }</pre> 
  34.  * 
  35.  * <p>To track the changing positions of the x/y coordinates, use 
  36.  * {@link #computeScrollOffset}. The method returns a boolean to indicate 
  37.  * whether the scroller is finished. If it isn't, it means that a fling or 
  38.  * programmatic pan operation is still in progress. You can use this method to 
  39.  * find the current offsets of the x and y coordinates, for example:</p> 
  40.  * 
  41.  * <pre>if (mScroller.computeScrollOffset()) { 
  42.  *     // Get current x and y positions 
  43.  *     int currX = mScroller.getCurrX(); 
  44.  *     int currY = mScroller.getCurrY(); 
  45.  *    ... 
  46.  * }</pre> 
  47.  */  
  48. public class Scroller  {  
  49.     private int mMode;  //分为SCROLL_MODE和FLING_MODE  
  50.   
  51.     private int mStartX;//起始坐标点,X轴方向  
  52.     private int mStartY;//起始坐标点,Y轴方向  
  53.     private int mFinalX;//滑动的最终位置,X轴方向  
  54.     private int mFinalY;//滑动的最终位置,Y轴方向  
  55.   
  56.     private int mMinX;  
  57.     private int mMaxX;  
  58.     private int mMinY;  
  59.     private int mMaxY;  
  60.   
  61.     private int mCurrX;//当前坐标点  X轴, 即调用startScroll函数后,经过一定时间所达到的值    
  62.     private int mCurrY;//当前坐标点  Y轴, 即调用startScroll函数后,经过一定时间所达到的值    
  63.     private long mStartTime;  
  64.     private int mDuration;  
  65.     private float mDurationReciprocal;  
  66.     private float mDeltaX;//应该继续滑动的距离, X轴方向  
  67.     private float mDeltaY;//应该继续滑动的距离, Y轴方向    
  68.     private boolean mFinished;//是否已经完成本次滑动操作, 如果完成则为 true    
  69.     // 被用来修饰动画效果,定义动画的变化率,可以使存在的动画效果accelerated(加速),decelerated(减速),repeated(重复),bounced(弹跳)等  
  70.     private Interpolator mInterpolator;  
  71.     private boolean mFlywheel;  
  72.   
  73.     private float mVelocity;  
  74.     private float mCurrVelocity;  
  75.     private int mDistance;  
  76.       
  77.     //ViewConfiguration包含了方法和标准的常量用来设置UI的超时、大小和距离   
  78.     private float mFlingFriction = ViewConfiguration.getScrollFriction();  
  79.   
  80.     private static final int DEFAULT_DURATION = 250;//默认的动画时间  
  81.     private static final int SCROLL_MODE = 0;  
  82.     private static final int FLING_MODE = 1;  
  83.   
  84.     private static float DECELERATION_RATE = (float) (Math.log(0.78) / Math.log(0.9));//滑动减速  
  85.     private static final float INFLEXION = 0.35f; // Tension lines cross at (INFLEXION, 1)  
  86.     private static final float START_TENSION = 0.5f;  
  87.     private static final float END_TENSION = 1.0f;  
  88.     private static final float P1 = START_TENSION * INFLEXION;  
  89.     private static final float P2 = 1.0f - END_TENSION * (1.0f - INFLEXION);  
  90.   
  91.     private static final int NB_SAMPLES = 100;  
  92.     private static final float[] SPLINE_POSITION = new float[NB_SAMPLES + 1];  
  93.     private static final float[] SPLINE_TIME = new float[NB_SAMPLES + 1];  
  94.   
  95.     private float mDeceleration;  
  96.     private final float mPpi;  
  97.   
  98.     // A context-specific coefficient adjusted to physical values.  
  99.     private float mPhysicalCoeff;  
  100.   
  101.     static {  
  102.         float x_min = 0.0f;  
  103.         float y_min = 0.0f;  
  104.         for (int i = 0; i < NB_SAMPLES; i++) {  
  105.             final float alpha = (float) i / NB_SAMPLES;  
  106.   
  107.             float x_max = 1.0f;  
  108.             float x, tx, coef;  
  109.             while (true) {  
  110.                 x = x_min + (x_max - x_min) / 2.0f;  
  111.                 coef = 3.0f * x * (1.0f - x);  
  112.                 tx = coef * ((1.0f - x) * P1 + x * P2) + x * x * x;  
  113.                 if (Math.abs(tx - alpha) < 1E-5break;  
  114.                 if (tx > alpha) x_max = x;  
  115.                 else x_min = x;  
  116.             }  
  117.             SPLINE_POSITION[i] = coef * ((1.0f - x) * START_TENSION + x) + x * x * x;  
  118.   
  119.             float y_max = 1.0f;  
  120.             float y, dy;  
  121.             while (true) {  
  122.                 y = y_min + (y_max - y_min) / 2.0f;  
  123.                 coef = 3.0f * y * (1.0f - y);  
  124.                 dy = coef * ((1.0f - y) * START_TENSION + y) + y * y * y;  
  125.                 if (Math.abs(dy - alpha) < 1E-5break;  
  126.                 if (dy > alpha) y_max = y;  
  127.                 else y_min = y;  
  128.             }  
  129.             SPLINE_TIME[i] = coef * ((1.0f - y) * P1 + y * P2) + y * y * y;  
  130.         }  
  131.         SPLINE_POSITION[NB_SAMPLES] = SPLINE_TIME[NB_SAMPLES] = 1.0f;  
  132.   
  133.         // This controls the viscous fluid effect (how much of it)  
  134.         sViscousFluidScale = 8.0f;  
  135.         // must be set to 1.0 (used in viscousFluid())  
  136.         sViscousFluidNormalize = 1.0f;  
  137.         sViscousFluidNormalize = 1.0f / viscousFluid(1.0f);  
  138.   
  139.     }  
  140.   
  141.     private static float sViscousFluidScale;  
  142.     private static float sViscousFluidNormalize;  
  143.   
  144.     /** 
  145.      * Create a Scroller with the default duration and interpolator. 
  146.      */  
  147.     public Scroller(Context context) {  
  148.         this(context, null);  
  149.     }  
  150.   
  151.     /** 
  152.      * Create a Scroller with the specified interpolator. If the interpolator is 
  153.      * null, the default (viscous) interpolator will be used. "Flywheel" behavior will 
  154.      * be in effect for apps targeting Honeycomb or newer. 
  155.      */  
  156.     public Scroller(Context context, Interpolator interpolator) {  
  157.         this(context, interpolator,  
  158.                 context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB);  
  159.     }  
  160.   
  161.     /** 
  162.      * Create a Scroller with the specified interpolator. If the interpolator is 
  163.      * null, the default (viscous) interpolator will be used. Specify whether or 
  164.      * not to support progressive "flywheel" behavior in flinging. 
  165.      */  
  166.     public Scroller(Context context, Interpolator interpolator, boolean flywheel) {  
  167.         mFinished = true;  
  168.         mInterpolator = interpolator;  
  169.         mPpi = context.getResources().getDisplayMetrics().density * 160.0f;  
  170.         mDeceleration = computeDeceleration(ViewConfiguration.getScrollFriction());  
  171.         mFlywheel = flywheel;  
  172.   
  173.         mPhysicalCoeff = computeDeceleration(0.84f); // look and feel tuning  
  174.     }  
  175.   
  176.     /** 
  177.      * The amount of friction applied to flings. The default value 
  178.      * is {@link ViewConfiguration#getScrollFriction}. 
  179.      *  
  180.      * @param friction A scalar dimension-less value representing the coefficient of 
  181.      *         friction. 
  182.      *摩擦,根据摩擦力,计算出减速 
  183.      */  
  184.     public final void setFriction(float friction) {  
  185.         mDeceleration = computeDeceleration(friction);  
  186.         mFlingFriction = friction;  
  187.     }  
  188.     //减速  
  189.     private float computeDeceleration(float friction) {  
  190.         return SensorManager.GRAVITY_EARTH   // g (m/s^2)  
  191.                       * 39.37f               // inch/meter  
  192.                       * mPpi                 // pixels per inch  
  193.                       * friction;  
  194.     }  
  195.   
  196.     /** 
  197.      *  
  198.      * Returns whether the scroller has finished scrolling. 
  199.      *  
  200.      * @return True if the scroller has finished scrolling, false otherwise. 
  201.      */  
  202.     public final boolean isFinished() {  
  203.         return mFinished;  
  204.     }  
  205.       
  206.     /** 
  207.      * Force the finished field to a particular value. 
  208.      *  //强制结束本次滑屏操作   
  209.      * @param finished The new finished value. 
  210.      */  
  211.     public final void forceFinished(boolean finished) {  
  212.         mFinished = finished;  
  213.     }  
  214.       
  215.     /** 
  216.      * Returns how long the scroll event will take, in milliseconds. 
  217.      *  
  218.      * @return The duration of the scroll in milliseconds. 
  219.      */  
  220.     public final int getDuration() {  
  221.         return mDuration;  
  222.     }  
  223.       
  224.     /** 
  225.      * Returns the current X offset in the scroll.  
  226.      *  
  227.      * @return The new X offset as an absolute distance from the origin. 
  228.      */  
  229.     public final int getCurrX() {  
  230.         return mCurrX;  
  231.     }  
  232.       
  233.     /** 
  234.      * Returns the current Y offset in the scroll.  
  235.      *  
  236.      * @return The new Y offset as an absolute distance from the origin. 
  237.      */  
  238.     public final int getCurrY() {  
  239.         return mCurrY;  
  240.     }  
  241.       
  242.     /** 
  243.      * Returns the current velocity. 
  244.      * 获取当前的速度,根据手势滑动还是自己滚动,如果是自己滚动,使用初始速度-减速,可能是负值 
  245.      * @return The original velocity less the deceleration. Result may be 
  246.      * negative. 
  247.      */  
  248.     public float getCurrVelocity() {  
  249.         return mMode == FLING_MODE ?  
  250.                 mCurrVelocity : mVelocity - mDeceleration * timePassed() / 2000.0f;  
  251.     }  
  252.   
  253.     /** 
  254.      * Returns the start X offset in the scroll.  
  255.      *  
  256.      * @return The start X offset as an absolute distance from the origin. 
  257.      */  
  258.     public final int getStartX() {  
  259.         return mStartX;  
  260.     }  
  261.       
  262.     /** 
  263.      * Returns the start Y offset in the scroll.  
  264.      *  
  265.      * @return The start Y offset as an absolute distance from the origin. 
  266.      */  
  267.     public final int getStartY() {  
  268.         return mStartY;  
  269.     }  
  270.       
  271.     /** 
  272.      * Returns where the scroll will end. Valid only for "fling" scrolls. 
  273.      *  
  274.      * @return The final X offset as an absolute distance from the origin. 
  275.      */  
  276.     public final int getFinalX() {  
  277.         return mFinalX;  
  278.     }  
  279.       
  280.     /** 
  281.      * Returns where the scroll will end. Valid only for "fling" scrolls. 
  282.      *  
  283.      * @return The final Y offset as an absolute distance from the origin. 
  284.      */  
  285.     public final int getFinalY() {  
  286.         return mFinalY;  
  287.     }  
  288.   
  289.     /** 
  290.      * Call this when you want to know the new location.  If it returns true, 
  291.      * the animation is not yet finished. 
  292.      * 返回值为boolean,true说明滚动尚未完成,false说明滚动已经完成。这是一个很重要的方法, 
  293.      * 通常放在View.computeScroll()中,用来判断是否滚动是否结束 
  294.      */   
  295.     public boolean computeScrollOffset() {  
  296.         if (mFinished) {//已经完成了本次动画控制,直接返回为false  
  297.             return false;  
  298.         }  
  299.         //动画使用的时间  
  300.         int timePassed = (int)(AnimationUtils.currentAnimationTimeMillis() - mStartTime);  
  301.       
  302.         if (timePassed < mDuration) {  
  303.             switch (mMode) {  
  304.             case SCROLL_MODE:  
  305.                 float x = timePassed * mDurationReciprocal;  
  306.       
  307.                 if (mInterpolator == null)  
  308.                     x = viscousFluid(x);   
  309.                 else  
  310.                     x = mInterpolator.getInterpolation(x);  
  311.       
  312.                 mCurrX = mStartX + Math.round(x * mDeltaX);  
  313.                 mCurrY = mStartY + Math.round(x * mDeltaY);  
  314.                 break;  
  315.             case FLING_MODE:  
  316.                 final float t = (float) timePassed / mDuration;  
  317.                 final int index = (int) (NB_SAMPLES * t);  
  318.                 float distanceCoef = 1.f;  
  319.                 float velocityCoef = 0.f;  
  320.                 if (index < NB_SAMPLES) {  
  321.                     final float t_inf = (float) index / NB_SAMPLES;  
  322.                     final float t_sup = (float) (index + 1) / NB_SAMPLES;  
  323.                     final float d_inf = SPLINE_POSITION[index];  
  324.                     final float d_sup = SPLINE_POSITION[index + 1];  
  325.                     velocityCoef = (d_sup - d_inf) / (t_sup - t_inf);  
  326.                     distanceCoef = d_inf + (t - t_inf) * velocityCoef;  
  327.                 }  
  328.   
  329.                 mCurrVelocity = velocityCoef * mDistance / mDuration * 1000.0f;  
  330.                   
  331.                 mCurrX = mStartX + Math.round(distanceCoef * (mFinalX - mStartX));  
  332.                 // Pin to mMinX <= mCurrX <= mMaxX  
  333.                 mCurrX = Math.min(mCurrX, mMaxX);  
  334.                 mCurrX = Math.max(mCurrX, mMinX);  
  335.                   
  336.                 mCurrY = mStartY + Math.round(distanceCoef * (mFinalY - mStartY));  
  337.                 // Pin to mMinY <= mCurrY <= mMaxY  
  338.                 mCurrY = Math.min(mCurrY, mMaxY);  
  339.                 mCurrY = Math.max(mCurrY, mMinY);  
  340.   
  341.                 if (mCurrX == mFinalX && mCurrY == mFinalY) {  
  342.                     mFinished = true;  
  343.                 }  
  344.   
  345.                 break;  
  346.             }  
  347.         }  
  348.         else {  
  349.             mCurrX = mFinalX;  
  350.             mCurrY = mFinalY;  
  351.             mFinished = true;  
  352.         }  
  353.         return true;  
  354.     }  
  355.       
  356.     /** 根据当前已经消逝的时间计算当前的坐标点,保存在mCurrX和mCurrY值中 
  357.      * Start scrolling by providing a starting point and the distance to travel. 
  358.      * The scroll will use the default value of 250 milliseconds for the 
  359.      * duration. 
  360.      * startX水平偏移量的起始位置,正号是向左滚动, 
  361.      * @param startX Starting horizontal scroll offset in pixels. Positive 
  362.      *        numbers will scroll the content to the left. 
  363.      *  startY竖直偏移量起始位置,正号是向上滚动 
  364.      * @param startY Starting vertical scroll offset in pixels. Positive numbers 
  365.      *        will scroll the content up. 
  366.      * dx水平滑动距离,+向左 
  367.      * @param dx Horizontal distance to travel. Positive numbers will scroll the 
  368.      *        content to the left. 
  369.      * dy竖直滑动距离,+向上 
  370.      * @param dy Vertical distance to travel. Positive numbers will scroll the 
  371.      *        content up. 
  372.      *开始一个动画控制,由(startX , startY)在duration时间内前进(dx,dy)个单位,到达坐标为 
  373.      *                 (startX+dx , startY+dy)处。 
  374.      */  
  375.     public void startScroll(int startX, int startY, int dx, int dy) {  
  376.         startScroll(startX, startY, dx, dy, DEFAULT_DURATION);  
  377.     }  
  378.   
  379.     /** 
  380.      * Start scrolling by providing a starting point, the distance to travel, 
  381.      * and the duration of the scroll. 
  382.      * 滚动,startX, startY为开始滚动的位置,dx,dy为滚动的偏移量, duration为完成滚动的时间 
  383.      * @param startX Starting horizontal scroll offset in pixels. Positive 
  384.      *        numbers will scroll the content to the left. 
  385.      * @param startY Starting vertical scroll offset in pixels. Positive numbers 
  386.      *        will scroll the content up. 
  387.      * @param dx Horizontal distance to travel. Positive numbers will scroll the 
  388.      *        content to the left. 
  389.      * @param dy Vertical distance to travel. Positive numbers will scroll the 
  390.      *        content up. 
  391.      * @param duration Duration of the scroll in milliseconds. 
  392.      */  
  393.     public void startScroll(int startX, int startY, int dx, int dy, int duration) {  
  394.         mMode = SCROLL_MODE;  
  395.         mFinished = false;  
  396.         mDuration = duration;  
  397.         mStartTime = AnimationUtils.currentAnimationTimeMillis();  
  398.         mStartX = startX;  
  399.         mStartY = startY;  
  400.         mFinalX = startX + dx;  
  401.         mFinalY = startY + dy;  
  402.         mDeltaX = dx;  
  403.         mDeltaY = dy;  
  404.         mDurationReciprocal = 1.0f / (float) mDuration;  
  405.     }  
  406.   
  407.     /** 
  408.      * Start scrolling based on a fling gesture. The distance travelled will 
  409.      * depend on the initial velocity of the fling. 
  410.      *  
  411.      * @param startX Starting point of the scroll (X) 
  412.      * @param startY Starting point of the scroll (Y) 
  413.      * @param velocityX Initial velocity of the fling (X) measured in pixels per 
  414.      *        second. 
  415.      * @param velocityY Initial velocity of the fling (Y) measured in pixels per 
  416.      *        second 
  417.      * @param minX Minimum X value. The scroller will not scroll past this 
  418.      *        point. 
  419.      * @param maxX Maximum X value. The scroller will not scroll past this 
  420.      *        point. 
  421.      * @param minY Minimum Y value. The scroller will not scroll past this 
  422.      *        point. 
  423.      * @param maxY Maximum Y value. The scroller will not scroll past this 
  424.      *        point. 
  425.      */  
  426.     public void fling(int startX, int startY, int velocityX, int velocityY,  
  427.             int minX, int maxX, int minY, int maxY) {  
  428.         // Continue a scroll or fling in progress  
  429.         if (mFlywheel && !mFinished) {  
  430.             float oldVel = getCurrVelocity();  
  431.   
  432.             float dx = (float) (mFinalX - mStartX);  
  433.             float dy = (float) (mFinalY - mStartY);  
  434.             float hyp = FloatMath.sqrt(dx * dx + dy * dy);  
  435.   
  436.             float ndx = dx / hyp;  
  437.             float ndy = dy / hyp;  
  438.   
  439.             float oldVelocityX = ndx * oldVel;  
  440.             float oldVelocityY = ndy * oldVel;  
  441.             if (Math.signum(velocityX) == Math.signum(oldVelocityX) &&  
  442.                     Math.signum(velocityY) == Math.signum(oldVelocityY)) {  
  443.                 velocityX += oldVelocityX;  
  444.                 velocityY += oldVelocityY;  
  445.             }  
  446.         }  
  447.   
  448.         mMode = FLING_MODE;  
  449.         mFinished = false;  
  450.   
  451.         float velocity = FloatMath.sqrt(velocityX * velocityX + velocityY * velocityY);  
  452.        
  453.         mVelocity = velocity;  
  454.         mDuration = getSplineFlingDuration(velocity);  
  455.         mStartTime = AnimationUtils.currentAnimationTimeMillis();  
  456.         mStartX = startX;  
  457.         mStartY = startY;  
  458.   
  459.         float coeffX = velocity == 0 ? 1.0f : velocityX / velocity;  
  460.         float coeffY = velocity == 0 ? 1.0f : velocityY / velocity;  
  461.   
  462.         double totalDistance = getSplineFlingDistance(velocity);  
  463.         mDistance = (int) (totalDistance * Math.signum(velocity));  
  464.           
  465.         mMinX = minX;  
  466.         mMaxX = maxX;  
  467.         mMinY = minY;  
  468.         mMaxY = maxY;  
  469.   
  470.         mFinalX = startX + (int) Math.round(totalDistance * coeffX);  
  471.         // Pin to mMinX <= mFinalX <= mMaxX  
  472.         mFinalX = Math.min(mFinalX, mMaxX);  
  473.         mFinalX = Math.max(mFinalX, mMinX);  
  474.           
  475.         mFinalY = startY + (int) Math.round(totalDistance * coeffY);  
  476.         // Pin to mMinY <= mFinalY <= mMaxY  
  477.         mFinalY = Math.min(mFinalY, mMaxY);  
  478.         mFinalY = Math.max(mFinalY, mMinY);  
  479.     }  
  480.       
  481.     private double getSplineDeceleration(float velocity) {  
  482.         return Math.log(INFLEXION * Math.abs(velocity) / (mFlingFriction * mPhysicalCoeff));  
  483.     }  
  484.   
  485.     private int getSplineFlingDuration(float velocity) {  
  486.         final double l = getSplineDeceleration(velocity);  
  487.         final double decelMinusOne = DECELERATION_RATE - 1.0;  
  488.         return (int) (1000.0 * Math.exp(l / decelMinusOne));  
  489.     }  
  490.   
  491.     private double getSplineFlingDistance(float velocity) {  
  492.         final double l = getSplineDeceleration(velocity);  
  493.         final double decelMinusOne = DECELERATION_RATE - 1.0;  
  494.         return mFlingFriction * mPhysicalCoeff * Math.exp(DECELERATION_RATE / decelMinusOne * l);  
  495.     }  
  496.   
  497.     static float viscousFluid(float x)  
  498.     {  
  499.         x *= sViscousFluidScale;  
  500.         if (x < 1.0f) {  
  501.             x -= (1.0f - (float)Math.exp(-x));  
  502.         } else {  
  503.             float start = 0.36787944117f;   // 1/e == exp(-1)  
  504.             x = 1.0f - (float)Math.exp(1.0f - x);  
  505.             x = start + x * (1.0f - start);  
  506.         }  
  507.         x *= sViscousFluidNormalize;  
  508.         return x;  
  509.     }  
  510.       
  511.     /** 
  512.      * Stops the animation. Contrary to {@link #forceFinished(boolean)}, 
  513.      * aborting the animating cause the scroller to move to the final x and y 
  514.      * position 
  515.      * 终止动画,直接滑动到指定位置 
  516.      * @see #forceFinished(boolean) 
  517.      */  
  518.     public void abortAnimation() {  
  519.         mCurrX = mFinalX;  
  520.         mCurrY = mFinalY;  
  521.         mFinished = true;  
  522.     }  
  523.       
  524.     /** 
  525.      * Extend the scroll animation. This allows a running animation to scroll 
  526.      * further and longer, when used with {@link #setFinalX(int)} or {@link #setFinalY(int)}. 
  527.      * 延长滚动时间 
  528.      * @param extend Additional time to scroll in milliseconds. 
  529.      * @see #setFinalX(int) 
  530.      * @see #setFinalY(int) 
  531.      */  
  532.     public void extendDuration(int extend) {  
  533.         int passed = timePassed();  
  534.         mDuration = passed + extend;  
  535.         mDurationReciprocal = 1.0f / mDuration;  
  536.         mFinished = false;  
  537.     }  
  538.   
  539.     /** 
  540.      * Returns the time elapsed since the beginning of the scrolling. 
  541.      * 获得滚动经历的时间 
  542.      * @return The elapsed time in milliseconds. 
  543.      */  
  544.     public int timePassed() {  
  545.         return (int)(AnimationUtils.currentAnimationTimeMillis() - mStartTime);  
  546.     }  
  547.   
  548.     /** 
  549.      * Sets the final position (X) for this scroller. 
  550.      *设置mScroller最终停留的水平位置,没有动画效果,直接跳到目标位置 
  551.      * @param newX The new X offset as an absolute distance from the origin. 
  552.      * @see #extendDuration(int) 
  553.      * @see #setFinalY(int) 
  554.      */  
  555.     public void setFinalX(int newX) {  
  556.         mFinalX = newX;  
  557.         mDeltaX = mFinalX - mStartX;  
  558.         mFinished = false;  
  559.     }  
  560.   
  561.     /** 
  562.      * Sets the final position (Y) for this scroller. 
  563.      *设置mScroller最终停留的竖直位置,没有动画效果,直接跳到目标位置 
  564.      * @param newY The new Y offset as an absolute distance from the origin. 
  565.      * @see #extendDuration(int) 
  566.      * @see #setFinalX(int) 
  567.      */  
  568.     public void setFinalY(int newY) {  
  569.         mFinalY = newY;  
  570.         mDeltaY = mFinalY - mStartY;  
  571.         mFinished = false;  
  572.     }  
  573.   
  574.     /** 
  575.      * @hide 
  576.      */  
  577.     public boolean isScrollingInDirection(float xvel, float yvel) {  
  578.         return !mFinished && Math.signum(xvel) == Math.signum(mFinalX - mStartX) &&  
  579.                 Math.signum(yvel) == Math.signum(mFinalY - mStartY);  
  580.     }  
  581. }</span><span style="font-size:24px;">  
  582. </span>  

2、Scroller调用关系

对于Scroller的调用,我先使用下面一张图片来阐述:


 Scroller的调用过程以及View的重绘:
  1 调用public void startScroll(int startX, int startY, int dx, int dy)
    该方法为scroll做一些准备工作.
    比如设置了移动的起始坐标,滑动的距离和方向以及持续时间等.
    该方法并不是真正的滑动scroll的开始,感觉叫prepareScroll()更贴切些.
    
  2 调用invalidate()或者postInvalidate()使View(ViewGroup)树重绘
    重绘会调用View的draw()方法
    draw()一共有六步: 
     Draw traversal performs several drawing steps which must be executed   
    in the appropriate order:   
    1. Draw the background   
    2. If necessary, save the canvas' layers to prepare for fading   
    3. Draw view's content   
    4. Draw children   
    5. If necessary, draw the fading edges and restore layers   
    6. Draw decorations (scrollbars for instance)
    其中最重要的是第三步和第四步
    第三步会去调用onDraw()绘制内容
    第四步会去调用dispatchDraw()绘制子View
    重绘分两种情况:
    2.1 ViewGroup的重绘
        在完成第三步onDraw()以后,进入第四步ViewGroup重写了
        父类View的dispatchDraw()绘制子View,于是这样继续调用:
        dispatchDraw()-->drawChild()-->child.computeScroll();
    2.2 View的重绘
        当View调用invalidate()方法时,会导致整个View树进行
        从上至下的一次重绘.比如从最外层的Layout到里层的Layout,直到每个子View.
        在重绘View树时ViewGroup和View时按理都会经过onMeasure()和onLayout()以及
        onDraw()方法.当然系统会判断这三个方法是否都必须执行,如果没有必要就不会调用.
        看到这里就明白了:当这个子View的父容器重绘时,也会调用上面提到的线路:
        onDraw()-->dispatchDraw()-->drawChild()-->child.computeScroll();
        于是子View(比如此处举例的ButtonSubClass类)中重写的computeScroll()方法
        就会被调用到.
        
  3 View树的重绘会调用到View中的computeScroll()方法
  
  4 在computeScroll()方法中
    在View的源码中可以看到public void computeScroll(){}是一个空方法.
    具体的实现需要自己来写.在该方法中我们可调用scrollTo()或scrollBy()
    来实现移动.该方法才是实现移动的核心.
    4.1 利用Scroller的mScroller.computeScrollOffset()判断移动过程是否完成
        注意:该方法是Scroller中的方法而不是View中的!!!!!!
        public boolean computeScrollOffset(){ }
        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.
        返回true时表示还移动还没有完成.
    4.2 若动画没有结束,则调用:scrollTo(By)();
        使其滑动scrolling
        
  5 再次调用invalidate().
    调用invalidate()方法那么又会重绘View树.
    从而跳转到第3步,如此循环,直到computeScrollOffset返回false
    
  通俗的理解:
  从上可见Scroller执行流程里面的三个核心方法
  mScroller.startScroll()
  mScroller.computeScrollOffset()
  view.computeScroll()
  1 在mScroller.startScroll()中为滑动做了一些初始化准备.
    比如:起始坐标,滑动的距离和方向以及持续时间(有默认值)等.
    其实除了这些,在该方法内还做了些其他事情:
    比较重要的一点是设置了动画开始时间.
  
  2 computeScrollOffset()方法主要是根据当前已经消逝的时间
    来计算当前的坐标点并且保存在mCurrX和mCurrY值中.
    因为在mScroller.startScroll()中设置了动画时间,那么
    在computeScrollOffset()方法中依据已经消逝的时间就很容易
    得到当前时刻应该所处的位置并将其保存在变量mCurrX和mCurrY中.
    除此之外该方法还可判断动画是否已经结束.
    
    所以在该示例中:
    @Override
    public void computeScroll() {
       super.computeScroll();
       if (mScroller.computeScrollOffset()) {
           scrollTo(mScroller.getCurrX(), 0);
           invalidate();
       }
    }
    先执行mScroller.computeScrollOffset()判断了滑动是否结束
    2.1 返回false,滑动已经结束.
    2.2 返回true,滑动还没有结束.
        并且在该方法内部也计算了最新的坐标值mCurrX和mCurrY.
        就是说在当前时刻应该滑动到哪里了.
        既然computeScrollOffset()如此贴心,盛情难却啊!
        于是我们就覆写View的computeScroll()方法,
        调用scrollTo(By)滑动到那里

3、Android中View绘制流程以及invalidate()等相关方法分析

关于这部分内容,大家可以查看Android中View绘制流程以及invalidate()等相关方法分析 这篇文章分析,里面详细介绍了onMeasure、onLayout、draw以及他们之间的关系,这里引用里面的一张图:


4、VelocityTracker、ViewConfiguration

VelocityTracker从字面意思理解那就是速度追踪器了,在滑动效果的开发中通常都是要使用该类计算出当前手势的初始速度,对应的方法是velocityTracker.computeCurrentVelocity(1000, mMaximumVelocity))并通过getXVelocity或getYVelocity方法得到对应的速度值initialVelocity,并将获得的速度值传递给Scroller类的fling(int startX, int startY, int velocityX, int velocityY, int minX, int maxX, int minY, int maxY) 方法进行控件滚动时各种位置坐标数值的计算,API中对fling 方法的解释是基于一个fling手势开始滑动动作,滑动的距离将由所获得的初始速度initialVelocity来决定。关于ViewConfiguration 的使用主要使用了该类的下面三个方法:

configuration.getScaledTouchSlop() //获得能够进行手势滑动的距离
configuration.getScaledMinimumFlingVelocity()//获得允许执行一个fling手势动作的最小速度值
configuration.getScaledMaximumFlingVelocity()//获得允许执行一个fling手势动作的最大速度值

需要重写的方法至少要包含下面几个方法:

onTouchEvent(MotionEvent event)//有手势操作必然少不了这个方法了

computeScroll()//必要时由父控件调用请求或通知其一个子节点需要更新它的mScrollX和mScrollY的值。典型的例子就是在一个子节点正在使用Scroller进行滑动动画时将会被执行。所以,从该方法的注释来看,继承这个方法的话一般都会有Scroller对象出现。

VelocityTracker的初始化以及资源释放的方法:
[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <span style="font-family:SimSun;font-size:18px;">private void obtainVelocityTracker(MotionEvent event) {  
  2.         if (mVelocityTracker == null) {  
  3.                 mVelocityTracker = VelocityTracker.obtain();  
  4.         }  
  5.         mVelocityTracker.addMovement(event);  
  6. }  
  7.   
  8. private void releaseVelocityTracker() {  
  9.         if (mVelocityTracker != null) {  
  10.                 mVelocityTracker.recycle();  
  11.                 mVelocityTracker = null;  
  12.         }</span>  
  13. }  

5、实例开发

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. package com.jwzhangjie.scrollview;  
  2.   
  3. import android.content.Context;  
  4. import android.util.AttributeSet;  
  5. import android.view.MotionEvent;  
  6. import android.view.VelocityTracker;  
  7. import android.view.View;  
  8. import android.view.ViewGroup;  
  9. import android.widget.Scroller;  
  10.   
  11. /** 
  12.  *  
  13.  * @author jwzhangjie 
  14.  */  
  15. public class MultiViewGroup extends ViewGroup {  
  16.   
  17.     private VelocityTracker mVelocityTracker; // 用于判断甩动手势  
  18.     private static final int SNAP_VELOCITY = 600// X轴速度基值,大于该值时进行切换  
  19.     private Scroller mScroller;// 滑动控制  
  20.     private int mCurScreen; // 当前页面为第几屏  
  21.     private int mDefaultScreen = 0;  
  22.     private float mLastMotionX;// 记住上次触摸屏的位置  
  23.     private int deltaX;  
  24.   
  25.     private OnViewChangeListener mOnViewChangeListener;  
  26.   
  27.     public MultiViewGroup(Context context) {  
  28.         this(context, null);  
  29.     }  
  30.   
  31.     public MultiViewGroup(Context context, AttributeSet attrs) {  
  32.         super(context, attrs);  
  33.         init(getContext());  
  34.     }  
  35.   
  36.     private void init(Context context) {  
  37.         mScroller = new Scroller(context);  
  38.         mCurScreen = mDefaultScreen;  
  39.     }  
  40.   
  41.     @Override  
  42.     public void computeScroll() {  
  43.         if (mScroller.computeScrollOffset()) {// 会更新Scroller中的当前x,y位置  
  44.             scrollTo(mScroller.getCurrX(), mScroller.getCurrY());  
  45.             postInvalidate();  
  46.         }  
  47.     }  
  48.   
  49.     @Override  
  50.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {  
  51.         super.onMeasure(widthMeasureSpec, heightMeasureSpec);  
  52.         int width = MeasureSpec.getSize(widthMeasureSpec);  
  53.         int count = getChildCount();  
  54.         for (int i = 0; i < count; i++) {  
  55.             measureChild(getChildAt(i), widthMeasureSpec, heightMeasureSpec);  
  56.             getChildAt(i).measure(widthMeasureSpec, heightMeasureSpec);  
  57.         }  
  58.         scrollTo(mCurScreen * width, 0);// 移动到第一页位置  
  59.     }  
  60.   
  61.     @Override  
  62.     protected void onLayout(boolean changed, int l, int t, int r, int b) {  
  63.         int margeLeft = 0;  
  64.         int size = getChildCount();  
  65.         for (int i = 0; i < size; i++) {  
  66.             View view = getChildAt(i);  
  67.             if (view.getVisibility() != View.GONE) {  
  68.                 int childWidth = view.getMeasuredWidth();  
  69.                 // 将内部子孩子横排排列  
  70.                 view.layout(margeLeft, 0, margeLeft + childWidth,  
  71.                         view.getMeasuredHeight());  
  72.                 margeLeft += childWidth;  
  73.             }  
  74.         }  
  75.     }  
  76.   
  77.     @Override  
  78.     public boolean onTouchEvent(MotionEvent event) {  
  79.         int action = event.getAction();  
  80.         float x = event.getX();  
  81.         switch (action) {  
  82.         case MotionEvent.ACTION_DOWN:  
  83.             obtainVelocityTracker(event);  
  84.             if (!mScroller.isFinished()) {  
  85.                 mScroller.abortAnimation();  
  86.             }  
  87.             mLastMotionX = x;  
  88.             break;  
  89.         case MotionEvent.ACTION_MOVE:  
  90.             deltaX = (int) (mLastMotionX - x);  
  91.             if (canMoveDis(deltaX)) {  
  92.                 obtainVelocityTracker(event);  
  93.                 mLastMotionX = x;  
  94.                 // 正向或者负向移动,屏幕跟随手指移动  
  95.                 scrollBy(deltaX, 0);  
  96.             }  
  97.             break;  
  98.         case MotionEvent.ACTION_UP:  
  99.         case MotionEvent.ACTION_CANCEL:  
  100.             // 当手指离开屏幕时,记录下mVelocityTracker的记录,并取得X轴滑动速度  
  101.             obtainVelocityTracker(event);  
  102.             mVelocityTracker.computeCurrentVelocity(1000);  
  103.             float velocityX = mVelocityTracker.getXVelocity();  
  104.             // 当X轴滑动速度大于SNAP_VELOCITY  
  105.             // velocityX为正值说明手指向右滑动,为负值说明手指向左滑动  
  106.             if (velocityX > SNAP_VELOCITY && mCurScreen > 0) {  
  107.                 // Fling enough to move left  
  108.                 snapToScreen(mCurScreen - 1);  
  109.             } else if (velocityX < -SNAP_VELOCITY  
  110.                     && mCurScreen < getChildCount() - 1) {  
  111.                 // Fling enough to move right  
  112.                 snapToScreen(mCurScreen + 1);  
  113.             } else {  
  114.                 snapToDestination();  
  115.             }  
  116.             releaseVelocityTracker();  
  117.             break;  
  118.         }  
  119.         // super.onTouchEvent(event);  
  120.         return true;// 这里一定要返回true,不然只接受down  
  121.     }  
  122.   
  123.     /** 
  124.      * 边界检测 
  125.      *  
  126.      * @param deltaX 
  127.      * @return 
  128.      */  
  129.     private boolean canMoveDis(int deltaX) {  
  130.         int scrollX = getScrollX();  
  131.         // deltaX<0说明手指向右划  
  132.         if (deltaX < 0) {  
  133.             if (scrollX <= 0) {  
  134.                 return false;  
  135.             } else if (deltaX + scrollX < 0) {  
  136.                 scrollTo(00);  
  137.                 return false;  
  138.             }  
  139.         }  
  140.         // deltaX>0说明手指向左划  
  141.         int leftX = (getChildCount() - 1) * getWidth();  
  142.         if (deltaX > 0) {  
  143.             if (scrollX >= leftX) {  
  144.                 return false;  
  145.             } else if (scrollX + deltaX > leftX) {  
  146.                 scrollTo(leftX, 0);  
  147.                 return false;  
  148.             }  
  149.         }  
  150.         return true;  
  151.     }  
  152.   
  153.     /** 
  154.      * 使屏幕移动到第whichScreen+1屏 
  155.      *  
  156.      * @param whichScreen 
  157.      */  
  158.     public void snapToScreen(int whichScreen) {  
  159.         int scrollX = getScrollX();  
  160.         if (scrollX != (whichScreen * getWidth())) {  
  161.             int delta = whichScreen * getWidth() - scrollX;  
  162.             mScroller.startScroll(scrollX, 0, delta, 0, Math.abs(delta) * 2);  
  163.             mCurScreen = whichScreen;  
  164.             invalidate();  
  165.             if (mOnViewChangeListener != null) {  
  166.                 mOnViewChangeListener.OnViewChange(mCurScreen);  
  167.             }  
  168.         }  
  169.     }  
  170.   
  171.     /** 
  172.      * 当不需要滑动时,会调用该方法 
  173.      */  
  174.     private void snapToDestination() {  
  175.         int screenWidth = getWidth();  
  176.         int whichScreen = (getScrollX() + (screenWidth / 2)) / screenWidth;  
  177.         snapToScreen(whichScreen);  
  178.     }  
  179.   
  180.     private void obtainVelocityTracker(MotionEvent event) {  
  181.         if (mVelocityTracker == null) {  
  182.             mVelocityTracker = VelocityTracker.obtain();  
  183.         }  
  184.         mVelocityTracker.addMovement(event);  
  185.     }  
  186.   
  187.     private void releaseVelocityTracker() {  
  188.         if (mVelocityTracker != null) {  
  189.             mVelocityTracker.recycle();  
  190.             mVelocityTracker = null;  
  191.         }  
  192.     }  
  193.   
  194.     public void SetOnViewChangeListener(OnViewChangeListener listener) {  
  195.         mOnViewChangeListener = listener;  
  196.     }  
  197.   
  198.     public interface OnViewChangeListener {  
  199.         public void OnViewChange(int page);  
  200.     }  
  201. }  

[java] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. package com.jwzhangjie.scrollview;  
  2.   
  3. import com.jwzhangjie.scrollview.MultiViewGroup.OnViewChangeListener;  
  4.   
  5. import android.os.Bundle;  
  6. import android.support.v4.app.FragmentActivity;  
  7. import android.view.View;  
  8. import android.widget.Toast;  
  9.   
  10. public class MultiActivity extends FragmentActivity implements  
  11.         OnViewChangeListener {  
  12.   
  13.     private MultiViewGroup multiViewGroup;  
  14.     private int allScreen;  
  15.     private int curreScreen = 0;  
  16.   
  17.     @Override  
  18.     protected void onCreate(Bundle bundle) {  
  19.         super.onCreate(bundle);  
  20.         setContentView(R.layout.activity_main);  
  21.         multiViewGroup = (MultiViewGroup) findViewById(R.id.screenParent);  
  22.         multiViewGroup.SetOnViewChangeListener(this);  
  23.         allScreen = multiViewGroup.getChildCount() - 1;  
  24.     }  
  25.   
  26.     public void nextScreen(View view) {  
  27.         if (curreScreen < allScreen) {  
  28.             curreScreen++;  
  29.         } else {  
  30.             curreScreen = 0;  
  31.   
  32.         }  
  33.         multiViewGroup.snapToScreen(curreScreen);  
  34.     }  
  35.   
  36.     public void preScreen(View view) {  
  37.         if (curreScreen > 0) {  
  38.             curreScreen--;  
  39.         } else {  
  40.             curreScreen = allScreen;  
  41.         }  
  42.         multiViewGroup.snapToScreen(curreScreen);  
  43.     }  
  44.   
  45.     @Override  
  46.     public void OnViewChange(int page) {  
  47.         Toast.makeText(getApplicationContext(),  
  48.                 getString(R.string.currePage, page), Toast.LENGTH_SHORT).show();  
  49.     }  
  50.   
  51. }  

[html] view plaincopyprint?在CODE上查看代码片派生到我的代码片
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     android:layout_width="match_parent"  
  3.     android:layout_height="match_parent" >  
  4.   
  5.     <Button  
  6.         android:id="@+id/nextPage"  
  7.         android:layout_width="wrap_content"  
  8.         android:layout_height="wrap_content"  
  9.         android:layout_margin="10dip"  
  10.         android:background="@drawable/bg_item_num_3_button"  
  11.         android:onClick="nextScreen"  
  12.         android:text="下一页" />  
  13.   
  14.     <Button  
  15.         android:id="@+id/prePage"  
  16.         android:layout_width="wrap_content"  
  17.         android:layout_height="wrap_content"  
  18.         android:layout_alignParentRight="true"  
  19.         android:layout_margin="10dip"  
  20.         android:background="@drawable/bg_item_num_3_button"  
  21.         android:onClick="preScreen"  
  22.         android:text="上一页" />  
  23.   
  24.     <com.jwzhangjie.scrollview.MultiViewGroup  
  25.         android:id="@+id/screenParent"  
  26.         android:layout_width="match_parent"  
  27.         android:layout_height="match_parent"  
  28.         android:layout_below="@id/nextPage" >  
  29.   
  30.         <LinearLayout  
  31.             android:layout_width="match_parent"  
  32.             android:layout_height="match_parent"  
  33.             android:background="#f00" >  
  34.   
  35.             <TextView  
  36.                 android:layout_width="wrap_content"  
  37.                 android:layout_height="wrap_content"  
  38.                 android:text="第一页" />  
  39.         </LinearLayout>  
  40.   
  41.         <LinearLayout  
  42.             android:layout_width="match_parent"  
  43.             android:layout_height="match_parent"  
  44.             android:background="#0f0" >  
  45.   
  46.             <TextView  
  47.                 android:layout_width="wrap_content"  
  48.                 android:layout_height="wrap_content"  
  49.                 android:text="第二页" />  
  50.         </LinearLayout>  
  51.   
  52.         <LinearLayout  
  53.             android:layout_width="match_parent"  
  54.             android:layout_height="match_parent"  
  55.             android:background="#00f" >  
  56.   
  57.             <TextView  
  58.                 android:layout_width="wrap_content"  
  59.                 android:layout_height="wrap_content"  
  60.                 android:text="第三页" />  
  61.         </LinearLayout>  
  62.     </com.jwzhangjie.scrollview.MultiViewGroup>  
  63.   
  64. </RelativeLayout>  

下载地址:https://github.com/jwzhangjie/MultiViewGroup

6、引用

1、Android中View绘制流程以及invalidate()等相关方法分析
2、Android 带你从源码的角度解析Scroller的滚动实现原理
3、 Android中滑屏实现----手把手教你如何实现触摸滑屏以及Scroller类详解

4、Android学习Scroller(五)——详解Scroller调用过程以及View的重绘
0 0