一、前言
上一篇文章中款慨,討論了View的幾種基本滑動方式儒飒,但是這些滑動方式是生硬的,在一瞬間完成的檩奠,這給用戶非常不好的體驗桩了,所以為了提高用戶體驗,我們需要將View彈性滑動埠戳。什么是彈性滑動井誉?就是一個View是在一段時間內(nèi)完成滑動的,而不是一瞬間完成的整胃,從原理來說颗圣,將一次滑動分解為若干個小的滑動,在一小段時間內(nèi)完成屁使,那么連貫起來就能看做一次彈性滑動在岂。本文將以彈性滑動方式之一:Scroller來講述其用法及原理。
二蛮寂、Scroller原理剖析
我們知道View自帶的scrollTo和scrollBy能實現(xiàn)View內(nèi)容的滑動蔽午,而Scroller則是基于這兩個方法而產(chǎn)生的一個輔助類,能使scrollTo/By的滑動變成彈性滑動一樣酬蹋,所以Scroller說到底也是用了scrollTo及老。那么Scroller是怎么使用的呢抽莱?其實Scroller有一個模板代碼,基本上實現(xiàn)彈性滑動都是這樣寫的骄恶,以下給出模板代碼:
//實例化Scroller對象岸蜗,在自定義View中,mContext可以在自定義View的構(gòu)造方法中獲取
Scroller mScroller = new Scroller(mContext);
//在一個自定義View中實現(xiàn)該方法叠蝇,方法名可以自定義
public void smoothScrollTo(int destX,int destY){
int scrollX = getScrollX();
int scrollY = getScrollY();
int dx = destX - scrollX;
int dy = destY - scrollY;
//前兩個參數(shù)表示起始位置,第三第四個參數(shù)表示位移量年缎,最后一個參數(shù)表示時間
mScroller.startScroll(scrollX,scrollY,dx,dy,1000);
invalidate();
}
//自定義View中重寫該方法
@Override
public void computeScroll(){
if(mScroller.computeScrollOffset()){
scrollTo(mScroller.getCurrX(),mScroller.getCurrY());
postInvalidate();
}
}
根據(jù)模板代碼可知悔捶,在一個View中實現(xiàn)smoothScrollTo()方法以及computeScroll()方法即可,那么這兩個方法到底有什么聯(lián)系呢单芜?以下從源碼層面分析:
(1)首先我們看Scroller的構(gòu)造方法:
public Scroller(Context context) {
this(context, null);
}
public Scroller(Context context, Interpolator interpolator) {
this(context, interpolator,context.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.HONEYCOMB);
}
由構(gòu)造方法可以知道蜕该,如果說只傳遞了一個Context值,那么會默認把Interpolator設置為null洲鸠,這里的Interpolator是插值器堂淡,所謂插值器,就是讓動畫按照某一規(guī)律來演示扒腕,比如說加速绢淀、減速、拋物線等瘾腰。
(2)接下來我們看smoothScrollTo(int,int):在這個方法里面皆的,其核心是startScroll()方法,我們先事先把參數(shù)計算好蹋盆,比如說當前的scrollX费薄、scrollY(當前偏移量),以及dx、dy(需要滑動的距離),然后把所得參數(shù)傳遞進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;
}
可以看出楞抡,該方法并無做實際的滑動,只是為scroller作一下參數(shù)的賦值析藕,mStartX召廷、mStartY表示滑動的起點;mFinalX,mFinalY表示滑動的終點噪径;mDeltalX,mDeltalY表示要滑動的距離柱恤;mStartTime記錄了滑動開始的時間。好吧找爱,這里沒有實際滑動的方法梗顺,那么接下來,我們看看View#invalidate()方法:
/**
* Invalidate the whole view. If the view is visible,
* {@link #onDraw(android.graphics.Canvas)} will be called at some point in
* the future.
* <p>
* This must be called from a UI thread. To call from a non-UI thread, call
* {@link #postInvalidate()}.
*/
public void invalidate() {
invalidate(true);
}
根據(jù)源碼注釋可以知道车摄,該方法最終會調(diào)用draw()方法寺谤,進行View的重繪仑鸥,至于invalidate()方法是怎樣調(diào)用到draw()方法,這里涉及到比較復雜的機制变屁,這里就不再提了眼俊。我們接著來看View#draw()方法:
/**
* Manually render this view (and all of its children) to the given Canvas.
* The view must have already done a full layout before this function is
* called. When implementing a view, implement
* {@link #onDraw(android.graphics.Canvas)} instead of overriding this method.
* If you do need to override this method, call the superclass version.
*
* @param canvas The Canvas to which the View is rendered.
*/
@CallSuper
public void draw(Canvas canvas) {
final int privateFlags = mPrivateFlags;
final boolean dirtyOpaque = (privateFlags & PFLAG_DIRTY_MASK) == PFLAG_DIRTY_OPAQUE &&
(mAttachInfo == null || !mAttachInfo.mIgnoreDirtyState);
mPrivateFlags = (privateFlags & ~PFLAG_DIRTY_MASK) | PFLAG_DRAWN;
/*
* 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)
*/
// Step 1, draw the background, if needed
int saveCount;
if (!dirtyOpaque) {
drawBackground(canvas);
}
// skip step 2 & 5 if possible (common case)
final int viewFlags = mViewFlags;
boolean horizontalEdges = (viewFlags & FADING_EDGE_HORIZONTAL) != 0;
boolean verticalEdges = (viewFlags & FADING_EDGE_VERTICAL) != 0;
if (!verticalEdges && !horizontalEdges) {
// Step 3, draw the content
if (!dirtyOpaque) onDraw(canvas);
// Step 4, draw the children
dispatchDraw(canvas);
// Overlay is part of the content and draws beneath Foreground
if (mOverlay != null && !mOverlay.isEmpty()) {
mOverlay.getOverlayView().dispatchDraw(canvas);
}
// Step 6, draw decorations (foreground, scrollbars)
onDrawForeground(canvas);
// we're done...
return;
}
......
源碼非常長,這里我們只挑重點來看粟关,根據(jù)上面的注釋疮胖,給出了draw流程的六個步驟,其中我們看step4闷板,draw the children:dispatchDraw(canvas),顧名思義澎灸,繪制當前View的子View,我們嘗試下追蹤源碼遮晚,會發(fā)現(xiàn)在View#dispatchDraw(canvas)中性昭,這是一個空實現(xiàn),那么肯定調(diào)用的不是當前View的dispatchDraw()方法县遣。我們前面提及過糜颠,使用scrollTo/By方法是對View的內(nèi)容進行滑動,那么這里調(diào)用的是ViewGroup#dispatchDraw(canvas)方法萧求,我們來看該方法:
@Override
protected void dispatchDraw(Canvas canvas) {
boolean usingRenderNodeProperties = canvas.isRecordingFor(mRenderNode);
final int childrenCount = mChildrenCount;
final View[] children = mChildren;
...
for (int i = 0; i < childrenCount; i++) {
while (transientIndex >= 0 && mTransientIndices.get(transientIndex) == i) {
final View transientChild = mTransientViews.get(transientIndex);
if ((transientChild.mViewFlags & VISIBILITY_MASK) == VISIBLE ||
transientChild.getAnimation() != null) {
more |= drawChild(canvas, transientChild, drawingTime);
...
}
}
}
...
}
方法也非常地長其兴,我們只看關鍵部分,首先在前面幾行代碼中饭聚,獲取到了childrenCount以及children[]數(shù)組忌警,表示當前ViewGroup需要繪制的子View的數(shù)量以及子View實例。接著在下面的一個for循環(huán)內(nèi)秒梳,對所有子View進行遍歷法绵,開始繪制子View,我們看drawChild()方法酪碘,ViewGroup#drawChild():
/**
* Draw one child of this View Group. This method is responsible for getting
* the canvas in the right state. This includes clipping, translating so
* that the child's scrolled origin is at 0, 0, and applying any animation
* transformations.
*
* @param canvas The canvas on which to draw the child
* @param child Who to draw
* @param drawingTime The time at which draw is occurring
* @return True if an invalidate() was issued
*/
protected boolean drawChild(Canvas canvas, View child, long drawingTime) {
return child.draw(canvas, this, drawingTime);
}
這里又調(diào)用了child.draw()朋譬,即View.draw()方法,上面已經(jīng)出現(xiàn)過這個方法了兴垦,但是徙赢,兩次的調(diào)用者不同。第一次調(diào)用的是ViewGroup調(diào)用draw()方法來對ViewGroup自身進行繪制探越,而這一次是子View對自身進行繪制狡赐,注意區(qū)分。我們再來看View#draw()方法:
...
int sx = 0;
int sy = 0;
if (!drawingWithRenderNode) {
computeScroll();
sx = mScrollX;
sy = mScrollY;
}
...
省略了一大部分代碼钦幔,我們可以看到上面出現(xiàn)了computeScroll()方法枕屉!終于,在經(jīng)過一系列的方法跳轉(zhuǎn)后鲤氢,我們找到了觸發(fā)computeScroll()方法的地方搀擂,在這里西潘,子View調(diào)用了computeScroll()方法,而View#computeScroll()是一個空實現(xiàn)哨颂,所以子View需要重寫這個方法以便我們實現(xiàn)接下來的邏輯喷市。
需要特別說明的是:這里的“子View”是指那些內(nèi)部有別的內(nèi)容的View,比如說一個ViewGroupA里面有一個ViewA威恼,那么需要對這個ViewA滑動品姓,我們可以重寫ViewGroupA的computeScroll()方法,這樣就做到了ViewGroupA內(nèi)容的滑動箫措,即ViewA的滑動了缭黔;如果重寫的是ViewA的computeScroll()方法,則不會達到滑動的效果蒂破,至于為什么,筆者在上一篇文章已經(jīng)說到了别渔,就是ScrollTo/By是針對View的內(nèi)容滑動的附迷。
接下來,我們看重寫的computeScroll()方法:
@Override
public void computeScroll(){
if(mScroller.computeScrollOffset()){ // 1
scrollTo(mScroller.getCurrX(),mScroller.getCurrY()); // 2
postInvalidate(); // 3
}
}
首先是一條if判斷語句哎媚,調(diào)用了Scroller.computeScrollOffset()方法喇伯,這個方法判斷是否還需要進行滑動,我們再看看這個方法到底干了什么:
/**
* Call this when you want to know the new location. If it returns true,
* the animation is not yet finished.
*/
public boolean computeScrollOffset() {
if (mFinished) {
return false;
}
int timePassed = (int)(AnimationUtils.currentAnimationTimeMillis() - mStartTime);
if (timePassed < mDuration) {
...
mCurrX = mStartX + Math.round(distanceCoef * (mFinalX - mStartX));
mCurrY = mStartY + Math.round(distanceCoef * (mFinalY - mStartY));
...
}
可以看到拨与,這里主要判斷了滑動時間與設置的時間的大小以及對mCurrX和mCurrY進行動態(tài)修改稻据,這樣每一次滑動都會向前滑動一點。
回到computeScroll()方法买喧,此時經(jīng)過computeScrollOffset()的判斷捻悯,如果還要進行滑動,則執(zhí)行scrollTo()方法淤毛,可以看到今缚,這里才實際上進行了View的滑動,接著進行postInvalidate()方法低淡,這個方法就是invalidate()方法姓言,只不過是在不同線程的情況下會調(diào)用該方法,那么蔗蹋,現(xiàn)在就很明朗了何荚,在computeScroll()的最后,再次調(diào)用了invalidate()方法猪杭,那么導致View樹進行第二次重繪餐塘,流程重新執(zhí)行一遍,再次調(diào)用computeScroll()胁孙,然后再次獲取currX和currY值唠倦,再次scrollTo...不斷重復称鳞,直到在①處判斷為false,跳出循環(huán)稠鼻,此時便完成了View的滑動過程冈止。
至此,Scroller的原理分析完畢候齿,以上說了一大堆熙暴,可能一時間很難接受,那么接下來就簡單總結(jié)一下整個流程:
建議各位讀者結(jié)合以上的流程圖來仔細體會Scroller的原理及流程慌盯,如果對Scroller的流程熟悉了周霉,那么利用Scroller進行View的滑動也會得心應手。限于篇幅關系亚皂,筆者將在下一篇文章中結(jié)合一個實例來講述Scroller的使用俱箱。