本文主要是介绍Scroller的使用用法,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Scroller是Android里面用于实现View的弹性滑动的一个Helper类,我们知道android里面ScrollTo,ScrollBy方法实现滑动的效果都是瞬时实现的,没有过渡的动画效果,这样体验式非常不好的,Scroller本身是无法实现滑动的,必须配合computeScroll才能共同完成这个功能。
private Scroller mScroller;
mScroller = new Scroller(getContext());
//缓慢滑动到指定位置
private void smoothScrollTo(int destX, int destY) {int scrollX = getScrollX();int deltaX = destX - scrollX;mScroller.startScroll(scrollX, 0, deltaX, 0, 1000);invalidate();//这个方法会导致View进行重绘,在View里面的Ondraw方法又会去调用computeScroll方法,//如此反复,直到滑动过程结束}
@Override
public void computeScroll() {if (mScroller.computeScrollOffset()) {scrollTo(mScroller.getCurrX(), mScroller.getCurrY());//通过mScroller对象获取到当前的X,Y坐标值postInvalidate(); //具体的获取方法看下边的computeScrollOffset方法}}
//Scroller里面的 computeScrollOffset方法源码
public boolean computeScrollOffset() {if (mFinished) {return false;}int timePassed = (int)(AnimationUtils.currentAnimationTimeMillis() - mStartTime);if (timePassed < mDuration) {switch (mMode) {case SCROLL_MODE:
<span style="white-space:pre"> </span>final float x = mInterpolator.getInterpolation(timePassed * mDurationReciprocal);mCurrX = mStartX + Math.round(x * mDeltaX);mCurrY = mStartY + Math.round(x * mDeltaY);break;case FLING_MODE:
<span style="white-space:pre"> </span>final float t = (float) timePassed / mDuration;
<span style="white-space:pre"> </span>final int index = (int) (NB_SAMPLES * t);float distanceCoef = 1.f;float velocityCoef = 0.f;if (index < NB_SAMPLES) {
<span style="white-space:pre"> </span>final float t_inf = (float) index / NB_SAMPLES;
<span style="white-space:pre"> </span>final float t_sup = (float) (index + 1) / NB_SAMPLES;
<span style="white-space:pre"> </span>final float d_inf = SPLINE_POSITION[index];
<span style="white-space:pre"> </span>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));//这里的mCurrX和下边的mCurrY就是X,Y坐标了// 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;}
这篇关于Scroller的使用用法的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!