滑动是我们在自定义控件时候经常遇见的难听,让新手们倍感困惑,这篇文章主要介绍Scroller类的源码,告诉打击这个到底有什么用,怎么使用它来控制滑动。另外,我还会结合一个简单的例子,来看一下这个类的应用。
要说明Scroller类,我们往往要从另外两个方法说起,一个是ScrollTo(),一个是ScrollBy()
这两个方法我们可以在View的源码看到,我们知道其实每个空间都有滚动条,只是有的我们将它隐藏,所以我们看不见
下面是ScrollTo方法
/** * Set the scrolled position of your view. This will cause a call to * {@link #onScrollChanged(int, int, int, int)} and the view will be * invalidated. * @param x the x position to scroll to * @param y the y position to scroll to */ public void scrollTo(int x, int y) {//滑动到的目标坐标 if (mScrollX != x || mScrollY != y) { int oldX = mScrollX;//已经滑动到的X int oldY = mScrollY;//已经滑动到的Y mScrollX = x; mScrollY = y; onScrollChanged(mScrollX, mScrollY, oldX, oldY);//调用说明状态改变 if (!awakenScrollBars()) { invalidate();//通知视图进行重绘 } } }
ScrollTo是一个public方法,说明我们可以在外部调用它,而正是我们调用了它,才能实现滑动,它的滑动效果是瞬间的,也就是说一步到位。
传进去的x,y是目的坐标,mScrollX,mScrollY是之前已经滑动到位置,调用这个函数以后,我们可以看到mScrollX,mScrollY被我们重新赋值,接下来会调用invalidate()进行重绘
那么滑动的本质是什么?根据动画移动的基本原理,对于一个控件来说,它的大小是有限的(例如我们可以自己设定,或者说被父控件所束缚)。所以我们绘图时会在这个有限的大小内进行绘制,但是控件的Canvas本质上是无限的,也就是一个控件的画布大小是无限,控件的大小就像一个窗口,我们只是通过这个窗口去看这块画布。
所以滑动的本质是,在窗口所见的画布部分,我们画些什么。
mScrollX,mScrollY起始是0,0,也就是说,窗口看见的,从画布的左上角开始的,然后我们改变两个值,例如100,100,窗口看见的,就是从100,100这个坐标开始绘制的东西(我们也可能没有在这块区域绘制东西,所以显示空白,因为画布是无限的)
说了这么多不知道大家有没有听懂,总之ScrollTo就是重新定义绘制起点坐标,从而实现滑动,由于绘制的一瞬间就开始的,所以ScrollTo造成的效果也是瞬间的
再来看看ScrollBy()方法
/** * Move the scrolled position of your view. This will cause a call to * {@link #onScrollChanged(int, int, int, int)} and the view will be * invalidated. * @param x the amount of pixels to scroll by horizontally * @param y the amount of pixels to scroll by vertically */ public void scrollBy(int x, int y) { scrollTo(mScrollX + x, mScrollY + y); }
它里面调用了ScrollTo(),那样我们就好理解了。传入的参数是mScrollX+x,也就是说这次x是一个增量,所以scrollBy实现的效果就是,在原来的起始位置,偏移x距离,再重新绘制,这是ScrollTo()和ScrollBy()的重要区别。
OK,上面讲了这么多,我们知道了用ScrollTo()就可以实现滑动了,但是我们需要的不是这样的滑动,我们希望滑动是有过程的,要缓慢的滑,要有feeling。
做javascript的朋友可能会想到,我使用一个for循环,然后每次调用ScrollBy()移动一定距离,每次移动后,让进程沉睡一段时间,不久可以实现动画的效果了吗?
是的,这是一般的思维,开始这样我们会面临两个问题,一个是让主线程沉睡(这是万万不能),一个是假设我们要实现多样的滑动算法(先快后慢,先慢后快等),怎么办?
其实cpu每个一定时间就会从新绘制画布(如果控件需要重新绘制的话),所以我们不必要让主线程沉睡,至于后面一个问题确实值得考虑。
直接地说,解决办法就是Scroller类,很多人看到这个类名,会不知道它跟滑动有什么关系。下面说一下,下面这段是Scroller的本质,只要听懂了,这篇文章就算没有白看了。
Scroller不能让控件滑动,之所以不能,因为本质上使控件滑动的是scrollTo()和scrollBy()方法
根据上面实现动画的思想,我们有必要每次调用ScrollTo方法前,计算出的新的x,y值,而Scroller就是替我们计算这两个值的
我们可以设定Scroller的内部算法(用于实现滑动物理的效果,我们不需要了解具体算法内容),然后调用Scroller的startScroll方法,这方法传入起始坐标,目的坐标,和滑动完成所需的时间,一旦调用这个方法以后,我们就可以通过它的getCurrX(),getCurrY()方法获得新的x,y坐标(这个两个坐标,是通过内部算法得来的)。
所以我们每次获得新坐标,然后scrollTo就行了,就可以实现滑动了。那么我们每次什么时候滑动呢(按照什么频率?难道真的写for循环?),当然是cpu绘制的频率最合理。
View里面有一个computeScroll()方法,在每次draw之前会调用,我们可以在调用这个方法时滑动(这个方法其实就是为我们滑动准备的啊!)
@Override public void computeScroll() { }
上面说的有点多,下面直接看scroller类源码
首先是一些属性,重要的我都有注释,没有注释的,是默认算法需要的,我们不必理睬
/** * 模式,有SCROLL_MODE和FLING_MODE */ private int mMode; /** * 起始x方向偏移 */ private int mStartX; /** * 起始y方向偏移 */ private int mStartY; /** * 终点x方向偏移 */ private int mFinalX; /** * 终点y方向偏移 */ private int mFinalY; private int mMinX; private int mMaxX; private int mMinY; private int mMaxY; /** * 当前x方向偏移 */ private int mCurrX; /** * 当前y方向偏移 */ private int mCurrY; /** * 起始时间 */ private long mStartTime; /** * 滚动持续时间 */ private int mDuration; /** * 持续时间的倒数 */ private float mDurationReciprocal; /** * x方向应该滚动的距离,mDeltaX=mFinalX-mStartX */ private float mDeltaX; /** * y方向应该滚动的距离,mDeltaY=mFinalY-mStartY */ private float mDeltaY; /** * 是否结束 */ private boolean mFinished; /** * 插值器 */ private Interpolator mInterpolator; /** * 调速轮 */ private boolean mFlywheel; private float mVelocity; /** * 默认滑动时间 */ private static final int DEFAULT_DURATION = 250; /** * 滑动模式 */ private static final int SCROLL_MODE = 0; /** * 猛冲模式 */ private static final int FLING_MODE = 1; private static float DECELERATION_RATE = (float) (Math.log(0.75) / Math.log(0.9)); private static float ALPHA = 800; // pixels / seconds private static float START_TENSION = 0.4f; // Tension at start: (0.4 * total T, 1.0 * Distance) private static float END_TENSION = 1.0f - START_TENSION; private static final int NB_SAMPLES = 100; private static final float[] SPLINE = new float[NB_SAMPLES + 1]; /** * 减速率 */ private float mDeceleration; /** * pixels per inch */ private final float mPpi;
然后来看构造函数
/** * Create a Scroller with the specified interpolator. If the interpolator is * null, the default (viscous) interpolator will be used. Specify whether or * not to support progressive "flywheel" behavior in flinging. * 通过Ppi和滑动摩擦因素,计算减速率 */ public Scroller(Context context, Interpolator interpolator, boolean flywheel) { mFinished = true; mInterpolator = interpolator; mPpi = context.getResources().getDisplayMetrics().density * 160.0f; mDeceleration = computeDeceleration(ViewConfiguration.getScrollFriction()); mFlywheel = flywheel; }
为控件创建scroller时,需要传入context,另外interpolator是插值器,不同的插值器实现不同的动画算法,如果我们不传,则使用scroller内部算法,接下面我就会看到
另外flywheel是flywheel,有版本的限制,一般也不会用到,也是用于滑动动画算法的实现
可以看到构造函数里面,只是做了一些设定,mFinished表示滑动是否结束
再来看很重要的startScroll()方法
/** * Start scrolling by providing a starting point and the distance to travel. * The scroll will use the default value of 250 milliseconds for the * duration. * * @param startX Starting horizontal scroll offset in pixels. Positive * numbers will scroll the content to the left. * @param startY Starting vertical scroll offset in pixels. Positive numbers * will scroll the content up. * @param dx Horizontal distance to travel. Positive numbers will scroll the * content to the left. * @param dy Vertical distance to travel. Positive numbers will scroll the * content up. * 使用默认滑动时间完成滑动 */ public void startScroll(int startX, int startY, int dx, int dy) { startScroll(startX, startY, dx, dy, DEFAULT_DURATION); } /** * Start scrolling by providing a starting point and the distance to travel. * * @param startX Starting horizontal scroll offset in pixels. Positive * numbers will scroll the content to the left. * 滑动起始X坐标 * @param startY Starting vertical scroll offset in pixels. Positive numbers * will scroll the content up. * 滑动起始Y坐标 * @param dx Horizontal distance to travel. Positive numbers will scroll the * content to the left. * X方向滑动距离 * @param dy Vertical distance to travel. Positive numbers will scroll the * content up. * Y方向滑动距离 * @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; mDuration = duration; mStartTime = AnimationUtils.currentAnimationTimeMillis();//获取当前时间作为滑动的起始时间 mStartX = startX; mStartY = startY; mFinalX = startX + dx; mFinalY = startY + dy; mDeltaX = dx; mDeltaY = dy; mDurationReciprocal = 1.0f / (float) mDuration; }
说它非常重要,但是内部却很简单,就是定义滑动的起始坐标,目的坐标和滑动时间,所以说根本没有实现滑动的效果
那么算法是在哪个方法里面调用的呢?
是computeScrollOffset()方法,这个方法返回false,说明滑动没有结束,但是它更重要的作用是,利用内部算法,起始坐标,目的坐标和滑动时间,从滑动开始到当前经过的时间,计算出新的坐标
所以说,我们在获取新的坐标前,一定要调用这个函数,这个函数的功能非常重要,而且并不简单!
/** * 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,说明滑动没有结束。 * getCurX(),getCurY()方法就可以获得计算后的值。 */ public boolean computeScrollOffset() { if (mFinished) {//是否结束 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);//计算当前X坐标 mCurrY = mStartY + Math.round(x * mDeltaY);//计算当前Y坐标 break; case FLING_MODE: final float t = (float) timePassed / mDuration; final int index = (int) (NB_SAMPLES * t); final float t_inf = (float) index / NB_SAMPLES; final float t_sup = (float) (index + 1) / NB_SAMPLES; final float d_inf = SPLINE[index]; final float d_sup = SPLINE[index + 1]; final float distanceCoef = d_inf + (t - t_inf) / (t_sup - t_inf) * (d_sup - d_inf); 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; }
从代码可以看到,如果我们没有设置插值器,就会调用内部默认算法。
/** * 函数翻译是粘性流体 * 估计是一种算法 */ static float viscousFluid(float x) { x *= sViscousFluidScale; if (x < 1.0f) { x -= (1.0f - (float)Math.exp(-x)); } else { float start = 0.36787944117f; // 1/e == exp(-1) x = 1.0f - (float)Math.exp(1.0f - x); x = start + x * (1.0f - start); } x *= sViscousFluidNormalize; return x; }
接着是两个重要的get方法
/** * Returns the current X offset in the scroll. * * @return The new X offset as an absolute distance from the origin. * 获得当前X方向偏移 */ public final int getCurrX() { return mCurrX; } /** * Returns the current Y offset in the scroll. * * @return The new Y offset as an absolute distance from the origin. * 获得当前Y方向偏移 */ public final int getCurrY() { return mCurrY; }
从scroller的整个源码,我们都可以看到,根本没有对控件进行重绘的操作。scroller只是一个利用滑动算法为控件提供新的绘制位置的工具,真正引起重绘的,是scrollTo方法,而这个方法需要我们主动调用(在computeScroll()里面)
另外scroller内部还有许多的get方法,还有强制停止动画效果的方法等,下面贴出scroller的完整代码和注释(我翻译得很烂,大家海涵),大家可以看看一下
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.widget; import android.content.Context; import android.hardware.SensorManager; import android.os.Build; import android.util.FloatMath; import android.view.ViewConfiguration; import android.view.animation.AnimationUtils; import android.view.animation.Interpolator; /** * This class encapsulates scrolling. The duration of the scroll * can be passed in the constructor and specifies the maximum time that * the scrolling animation should take. Past this time, the scrolling is * automatically moved to its final stage and computeScrollOffset() * will always return false to indicate that scrolling is over. * 这个类封装了滑动。滑动时间可以通过构造函数传入,并且制定滑动动画完成所需的最大时间。 * 这个时间以后,将会自动滑动到它的最终状态,并且computeScrollOffset()将返回false,表示滑动结束 */ public class Scroller { /** * 模式,有SCROLL_MODE和FLING_MODE */ private int mMode; /** * 起始x方向偏移 */ private int mStartX; /** * 起始y方向偏移 */ private int mStartY; /** * 终点x方向偏移 */ private int mFinalX; /** * 终点y方向偏移 */ private int mFinalY; private int mMinX; private int mMaxX; private int mMinY; private int mMaxY; /** * 当前x方向偏移 */ private int mCurrX; /** * 当前y方向偏移 */ private int mCurrY; /** * 起始时间 */ private long mStartTime; /** * 滚动持续时间 */ private int mDuration; /** * 持续时间的倒数 */ private float mDurationReciprocal; /** * x方向应该滚动的距离,mDeltaX=mFinalX-mStartX */ private float mDeltaX; /** * y方向应该滚动的距离,mDeltaY=mFinalY-mStartY */ private float mDeltaY; /** * 是否结束 */ private boolean mFinished; /** * 插值器 */ private Interpolator mInterpolator; /** * 调速轮 */ private boolean mFlywheel; private float mVelocity; /** * 默认滑动时间 */ private static final int DEFAULT_DURATION = 250; /** * 滑动模式 */ private static final int SCROLL_MODE = 0; /** * 猛冲模式 */ private static final int FLING_MODE = 1; private static float DECELERATION_RATE = (float) (Math.log(0.75) / Math.log(0.9)); private static float ALPHA = 800; // pixels / seconds private static float START_TENSION = 0.4f; // Tension at start: (0.4 * total T, 1.0 * Distance) private static float END_TENSION = 1.0f - START_TENSION; private static final int NB_SAMPLES = 100; private static final float[] SPLINE = new float[NB_SAMPLES + 1]; /** * 减速率 */ private float mDeceleration; /** * pixels per inch */ private final float mPpi; static { float x_min = 0.0f; for (int i = 0; i <= NB_SAMPLES; i++) { final float t = (float) i / NB_SAMPLES; float x_max = 1.0f; float x, tx, coef; while (true) { x = x_min + (x_max - x_min) / 2.0f; coef = 3.0f * x * (1.0f - x); tx = coef * ((1.0f - x) * START_TENSION + x * END_TENSION) + x * x * x; if (Math.abs(tx - t) < 1E-5) break; if (tx > t) x_max = x; else x_min = x; } final float d = coef + x * x * x; SPLINE[i] = d; } SPLINE[NB_SAMPLES] = 1.0f; // This controls the viscous fluid effect (how much of it) sViscousFluidScale = 8.0f; // must be set to 1.0 (used in viscousFluid()) sViscousFluidNormalize = 1.0f; sViscousFluidNormalize = 1.0f / viscousFluid(1.0f); } private static float sViscousFluidScale; private static float sViscousFluidNormalize; /** * Create a Scroller with the default duration and interpolator. * 默认滑动时间和插值器 */ public Scroller(Context context) { this(context, null); } /** * Create a Scroller with the specified interpolator. If the interpolator is * null, the default (viscous) interpolator will be used. "Flywheel" behavior will * be in effect for apps targeting Honeycomb or newer. * 调速轮只能在Honeycomb以上的版本有效 */ public Scroller(Context context, Interpolator interpolator) { this(context, interpolator, context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB); } /** * Create a Scroller with the specified interpolator. If the interpolator is * null, the default (viscous) interpolator will be used. Specify whether or * not to support progressive "flywheel" behavior in flinging. * 通过Ppi和滑动摩擦因素,计算减速率 */ public Scroller(Context context, Interpolator interpolator, boolean flywheel) { mFinished = true; mInterpolator = interpolator; mPpi = context.getResources().getDisplayMetrics().density * 160.0f; mDeceleration = computeDeceleration(ViewConfiguration.getScrollFriction()); mFlywheel = flywheel; } /** * The amount of friction applied to flings. The default value * is {@link ViewConfiguration#getScrollFriction}. * * @param friction A scalar dimension-less value representing the coefficient of * friction. * 设置fling方法的摩擦因素大小 */ public final void setFriction(float friction) { mDeceleration = computeDeceleration(friction); } /** * 计算减速率 */ private float computeDeceleration(float friction) { return SensorManager.GRAVITY_EARTH // g (m/s^2) * 39.37f // inch/meter * mPpi // pixels per inch * friction; } /** * * Returns whether the scroller has finished scrolling. * * @return True if the scroller has finished scrolling, false otherwise. * 判断滑动是否停止 */ public final boolean isFinished() { return mFinished; } /** * Force the finished field to a particular value. * * @param finished The new finished value. * 强制滑动停止 */ public final void forceFinished(boolean finished) { mFinished = finished; } /** * Returns how long the scroll event will take, in milliseconds. * * @return The duration of the scroll in milliseconds. * 获得滑动时间 */ public final int getDuration() { return mDuration; } /** * Returns the current X offset in the scroll. * * @return The new X offset as an absolute distance from the origin. * 获得当前X方向偏移 */ public final int getCurrX() { return mCurrX; } /** * Returns the current Y offset in the scroll. * * @return The new Y offset as an absolute distance from the origin. * 获得当前Y方向偏移 */ public final int getCurrY() { return mCurrY; } /** * Returns the current velocity. * * @return The original velocity less the deceleration. Result may be * negative. */ public float getCurrVelocity() { return mVelocity - mDeceleration * timePassed() / 2000.0f; } /** * Returns the start X offset in the scroll. * * @return The start X offset as an absolute distance from the origin. */ public final int getStartX() { return mStartX; } /** * Returns the start Y offset in the scroll. * * @return The start Y offset as an absolute distance from the origin. */ public final int getStartY() { return mStartY; } /** * Returns where the scroll will end. Valid only for "fling" scrolls. * * @return The final X offset as an absolute distance from the origin. */ public final int getFinalX() { return mFinalX; } /** * Returns where the scroll will end. Valid only for "fling" scrolls. * * @return The final Y offset as an absolute distance from the origin. */ public final int getFinalY() { return mFinalY; } /** * 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,说明滑动没有结束。 * getCurX(),getCurY()方法就可以获得计算后的值。 */ public boolean computeScrollOffset() { if (mFinished) {//是否结束 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);//计算当前X坐标 mCurrY = mStartY + Math.round(x * mDeltaY);//计算当前Y坐标 break; case FLING_MODE: final float t = (float) timePassed / mDuration; final int index = (int) (NB_SAMPLES * t); final float t_inf = (float) index / NB_SAMPLES; final float t_sup = (float) (index + 1) / NB_SAMPLES; final float d_inf = SPLINE[index]; final float d_sup = SPLINE[index + 1]; final float distanceCoef = d_inf + (t - t_inf) / (t_sup - t_inf) * (d_sup - d_inf); 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; } /** * Start scrolling by providing a starting point and the distance to travel. * The scroll will use the default value of 250 milliseconds for the * duration. * * @param startX Starting horizontal scroll offset in pixels. Positive * numbers will scroll the content to the left. * @param startY Starting vertical scroll offset in pixels. Positive numbers * will scroll the content up. * @param dx Horizontal distance to travel. Positive numbers will scroll the * content to the left. * @param dy Vertical distance to travel. Positive numbers will scroll the * content up. * 使用默认滑动时间完成滑动 */ public void startScroll(int startX, int startY, int dx, int dy) { startScroll(startX, startY, dx, dy, DEFAULT_DURATION); } /** * Start scrolling by providing a starting point and the distance to travel. * * @param startX Starting horizontal scroll offset in pixels. Positive * numbers will scroll the content to the left. * 滑动起始X坐标 * @param startY Starting vertical scroll offset in pixels. Positive numbers * will scroll the content up. * 滑动起始Y坐标 * @param dx Horizontal distance to travel. Positive numbers will scroll the * content to the left. * X方向滑动距离 * @param dy Vertical distance to travel. Positive numbers will scroll the * content up. * Y方向滑动距离 * @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; mDuration = duration; mStartTime = AnimationUtils.currentAnimationTimeMillis();//获取当前时间作为滑动的起始时间 mStartX = startX; mStartY = startY; mFinalX = startX + dx; mFinalY = startY + dy; mDeltaX = dx; mDeltaY = dy; mDurationReciprocal = 1.0f / (float) mDuration; } /** * Start scrolling based on a fling gesture. The distance travelled will * depend on the initial velocity of the fling. * * @param startX Starting point of the scroll (X) * @param startY Starting point of the scroll (Y) * @param velocityX Initial velocity of the fling (X) measured in pixels per * second. * @param velocityY Initial velocity of the fling (Y) measured in pixels per * second * @param minX Minimum X value. The scroller will not scroll past this * point. * @param maxX Maximum X value. The scroller will not scroll past this * point. * @param minY Minimum Y value. The scroller will not scroll past this * point. * @param maxY Maximum Y value. The scroller will not scroll past this * point. * 开始基于滑动手势的滑动。根据初始的滑动手势速度,决定滑动的距离(滑动的距离,不能大于设定的最大值,不能小于设定的最小值) */ public void fling(int startX, int startY, int velocityX, int velocityY, int minX, int maxX, int minY, int maxY) { // Continue a scroll or fling in progress if (mFlywheel && !mFinished) { float oldVel = getCurrVelocity(); float dx = (float) (mFinalX - mStartX); float dy = (float) (mFinalY - mStartY); float hyp = FloatMath.sqrt(dx * dx + dy * dy); float ndx = dx / hyp; float ndy = dy / hyp; float oldVelocityX = ndx * oldVel; float oldVelocityY = ndy * oldVel; if (Math.signum(velocityX) == Math.signum(oldVelocityX) && Math.signum(velocityY) == Math.signum(oldVelocityY)) { velocityX += oldVelocityX; velocityY += oldVelocityY; } } mMode = FLING_MODE; mFinished = false; float velocity = FloatMath.sqrt(velocityX * velocityX + velocityY * velocityY); mVelocity = velocity; final double l = Math.log(START_TENSION * velocity / ALPHA); mDuration = (int) (1000.0 * Math.exp(l / (DECELERATION_RATE - 1.0))); mStartTime = AnimationUtils.currentAnimationTimeMillis(); mStartX = startX; mStartY = startY; float coeffX = velocity == 0 ? 1.0f : velocityX / velocity; float coeffY = velocity == 0 ? 1.0f : velocityY / velocity; int totalDistance = (int) (ALPHA * Math.exp(DECELERATION_RATE / (DECELERATION_RATE - 1.0) * l)); mMinX = minX; mMaxX = maxX; mMinY = minY; mMaxY = maxY; mFinalX = startX + Math.round(totalDistance * coeffX); // Pin to mMinX <= mFinalX <= mMaxX mFinalX = Math.min(mFinalX, mMaxX); mFinalX = Math.max(mFinalX, mMinX); mFinalY = startY + Math.round(totalDistance * coeffY); // Pin to mMinY <= mFinalY <= mMaxY mFinalY = Math.min(mFinalY, mMaxY); mFinalY = Math.max(mFinalY, mMinY); } /** * 函数翻译是粘性流体 * 估计是一种算法 */ static float viscousFluid(float x) { x *= sViscousFluidScale; if (x < 1.0f) { x -= (1.0f - (float)Math.exp(-x)); } else { float start = 0.36787944117f; // 1/e == exp(-1) x = 1.0f - (float)Math.exp(1.0f - x); x = start + x * (1.0f - start); } x *= sViscousFluidNormalize; return x; } /** * Stops the animation. Contrary to {@link #forceFinished(boolean)}, * aborting the animating cause the scroller to move to the final x and y * position * * @see #forceFinished(boolean) * 强制停止滑动动画,并且将目的坐标设置为当前坐标 */ public void abortAnimation() { mCurrX = mFinalX; mCurrY = mFinalY; mFinished = true; } /** * Extend the scroll animation. This allows a running animation to scroll * further and longer, when used with {@link #setFinalX(int)} or {@link #setFinalY(int)}. * * @param extend Additional time to scroll in milliseconds. * @see #setFinalX(int) * @see #setFinalY(int) * 延长滚动时间 */ public void extendDuration(int extend) { int passed = timePassed(); mDuration = passed + extend; mDurationReciprocal = 1.0f / mDuration; mFinished = false; } /** * Returns the time elapsed since the beginning of the scrolling. * * @return The elapsed time in milliseconds. * 获得已经滚动的时间 */ public int timePassed() { return (int)(AnimationUtils.currentAnimationTimeMillis() - mStartTime); } /** * Sets the final position (X) for this scroller. * * @param newX The new X offset as an absolute distance from the origin. * @see #extendDuration(int) * @see #setFinalY(int) * 设置mScroller最终停留的水平位置,没有动画效果,直接跳到目标位置 */ public void setFinalX(int newX) { mFinalX = newX; mDeltaX = mFinalX - mStartX; mFinished = false; } /** * Sets the final position (Y) for this scroller. * * @param newY The new Y offset as an absolute distance from the origin. * @see #extendDuration(int) * @see #setFinalX(int) * 设置mScroller最终停留的竖直位置,没有动画效果,直接跳到目标位置 */ public void setFinalY(int newY) { mFinalY = newY; mDeltaY = mFinalY - mStartY; mFinished = false; } /** * @hide */ public boolean isScrollingInDirection(float xvel, float yvel) { return !mFinished && Math.signum(xvel) == Math.signum(mFinalX - mStartX) && Math.signum(yvel) == Math.signum(mFinalY - mStartY); } }
更重要的是创建scroller来解决问题的这种思想,有点像记账簿模式(记不清了,但肯定是设计模式的一种体现)
对应scroller的具体应用,还有手势滑动等内容,大家可以参看下一篇文章。