Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

深入View體系:從源碼透視Scroller的滑動奧秘

編輯:關於 Android 開發

深入View體系:從源碼透視Scroller的滑動奧秘

前言

在《Android View體系(二):實現View滑動的六種方法》一文中,我們曾談到用Scroller來驅動View滑動。既然用法已有交代,本篇就不再贅述如何使用,而是帶大家潛入源碼深處,看看Scroller究竟憑什麼能讓View平滑地滑動起來。

一、Scroller的構造函數

要使用Scroller,第一步自然是new一個對象出來。我們先來看看它的構造函數:

/** * 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. */ 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. */ public Scroller(Context context, Interpolator interpolator, boolean flywheel) { mFinished = true; if (interpolator == null) { mInterpolator = new ViscousFluidInterpolator(); } else { mInterpolator = interpolator; } mPpi = context.getResources().getDisplayMetrics().density * 160.0f; mDeceleration = computeDeceleration(ViewConfiguration.getScrollFriction()); mFlywheel = flywheel; mPhysicalCoeff = computeDeceleration(0.84f); // look and feel tuning }

Scroller提供了三個構造函數,日常開發中我們最常用的是第一個。第二個可以讓你傳入自定義的插值器Interpolator,若不傳則默認使用系統的viscous插值器。

二、Scroller的startScroll方法

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; }

仔細觀察會發現,startScroll()並沒有調用任何「開啟滑動」的方法,它只是老老實實地把傳入的參數保存下來:startX、startY是滑動起點,dx、dy是滑動距離,duration則是持續時間。換句話說,startScroll()僅僅完成了前期準備工作,並不能真正讓View動起來。

真正的關鍵在於:我們在調用startScroll()之後緊接著調用了invalidate()。這個方法會觸發View的重繪,而重繪過程會調用View的draw()方法,draw()內部又會調用computeScroll()。於是我們重寫computeScroll():

@Override public void computeScroll() { super.computeScroll(); if(mScroller.computeScrollOffset()){ ((View) getParent()).scrollTo(mScroller.getCurrX(),mScroller.getCurrY()); //通過不斷的重繪不斷的調用computeScroll方法 invalidate(); } }

在computeScroll()中,我們通過Scroller取得當前橫縱坐標,再調用scrollTo()完成實際的位移,隨後再次調用invalidate()讓View重繪,重繪又會觸發computeScroll(),如此循環往復,便實現了滑動。把每一次微小的位移連綴起來,最終呈現的就是流暢自然的移動效果。

但問題來了:Scroller是怎麼算出當前位置的ScrollX和ScrollY的呢?答案就藏在scrollTo()之前調用的computeScrollOffset()方法裡,下面我們就來拆解它。

三、Scroller的computeScrollOffset方法

public boolean computeScrollOffset() { if (mFinished) { return false; } //動畫持續的時間 int timePassed = (int)(AnimationUtils.currentAnimationTimeMillis() - mStartTime); if (timePassed < mDuration) { switch (mMode) { case SCROLL_MODE: final float x = mInterpolator.getInterpolation(timePassed * mDurationReciprocal); //根據插值器來算出timePassed這段時間移動的距離 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 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; }

方法首先算出動畫已經流逝的時間timePassed。若它小於我們設置的滑動時長mDuration,就進入switch分支。由於startScroll()中把mMode設為SCROLL_MODE,因此會走SCROLL_MODE分支:此時借助插值器Interpolator計算出這段時間內應該移動的比例,再換算成具體距離賦給mCurrX和mCurrY。至此,我們便能通過Scroller拿到當前的橫縱坐標了。

值得一提的是,computeScrollOffset()的返回值別有深意:返回true代表滑動尚未結束,返回false則表示滑動已經完成。所以只要滑動還沒結束,我們就得持續調用scrollTo()與invalidate(),讓View一幀一幀地滑到底。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved