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

SwipeRefreshLayout 下拉刷新控件源碼解析

編輯:關於 Android 程式設計

SwipeRefreshLayout 是 Android 官方提供的下拉刷新控件,使用簡單、界面美觀。本文直接進入正題,梳理它的運作流程。

整體原理

這類下拉刷新控件的原理並不複雜:監聽手指運動、取得座標,透過計算判斷是哪一種操作,再回呼相應介面。SwipeRefreshLayout 繼承自 ViewGroup,依據 Android 的事件分發機制,觸摸事件會先傳到 ViewGroup,再由 onInterceptTouchEvent 的返回值決定是否攔截。先看這個方法:

 @Override public boolean onInterceptTouchEvent(MotionEvent ev) { ensureTarget(); final int action = MotionEventCompat.getActionMasked(ev); if (mReturningToStart && action == MotionEvent.ACTION_DOWN) { mReturningToStart = false; } if (!isEnabled() || mReturningToStart || canChildScrollUp() || mRefreshing || mNestedScrollInProgress) { // Fail fast if we're not in a state where a swipe is possible return false; } switch (action) { case MotionEvent.ACTION_DOWN: setTargetOffsetTopAndBottom(mOriginalOffsetTop - mCircleView.getTop(), true); mActivePointerId = MotionEventCompat.getPointerId(ev, 0); mIsBeingDragged = false; final float initialDownY = getMotionEventY(ev, mActivePointerId); if (initialDownY == -1) { return false; } mInitialDownY = initialDownY; break; case MotionEvent.ACTION_MOVE: if (mActivePointerId == INVALID_POINTER) { Log.e(LOG_TAG, "Got ACTION_MOVE event but don't have an active pointer id."); return false; } final float y = getMotionEventY(ev, mActivePointerId); if (y == -1) { return false; } final float yDiff = y - mInitialDownY; if (yDiff > mTouchSlop && !mIsBeingDragged) { mInitialMotionY = mInitialDownY + mTouchSlop; mIsBeingDragged = true; mProgress.setAlpha(STARTING_PROGRESS_ALPHA); } break; case MotionEventCompat.ACTION_POINTER_UP: onSecondaryPointerUp(ev); break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: mIsBeingDragged = false; mActivePointerId = INVALID_POINTER; break; } return mIsBeingDragged; } 

是否攔截有多種情況,這裡只要滿足五個條件之一就直接回傳 false。使用時若遇到觸摸事件衝突,就可以從這段著手分析。簡單說:ACTION_DOWN 記錄手指座標,ACTION_MOVE 計算移動距離並與閾值比較,超過就將 mIsBeingDragged 設為 true,ACTION_UP 則設回 false,最後回傳 mIsBeingDragged。

SwipeRefreshLayout 通常搭配可捲動的 View 使用。正常捲動時會滿足前述條件而不攔截,只有捲到頂部時才進入後續判斷。在按下到抬起之間 mIsBeingDragged 為 true,代表進行攔截,接下來就交給 onTouchEvent 處理:

 @Override public boolean onTouchEvent(MotionEvent ev) { .... switch (action) { case MotionEvent.ACTION_DOWN: mActivePointerId = MotionEventCompat.getPointerId(ev, 0); mIsBeingDragged = false; break; case MotionEvent.ACTION_MOVE: { pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); if (pointerIndex < 0) { Log.e(LOG_TAG, "Got ACTION_MOVE event but have an invalid active pointer id."); return false; } final float y = MotionEventCompat.getY(ev, pointerIndex); final float overscrollTop = (y - mInitialMotionY) * DRAG_RATE; if (mIsBeingDragged) { if (overscrollTop > 0) { moveSpinner(overscrollTop); } else { return false; } } break; } .... case MotionEvent.ACTION_UP: { pointerIndex = MotionEventCompat.findPointerIndex(ev, mActivePointerId); if (pointerIndex < 0) { Log.e(LOG_TAG, "Got ACTION_UP event but don't have an active pointer id."); return false; } final float y = MotionEventCompat.getY(ev, pointerIndex); final float overscrollTop = (y - mInitialMotionY) * DRAG_RATE; mIsBeingDragged = false; finishSpinner(overscrollTop); mActivePointerId = INVALID_POINTER; return false; } case MotionEvent.ACTION_CANCEL: return false; } return true; } 

ACTION_MOVE 中算出手指移動距離,大於零就執行 moveSpinner;ACTION_UP 則執行 finishSpinner。可以推測,刷新的主要邏輯就在這兩個方法裡。

兩個關鍵成員變量

分析之前,先認識兩個重要變量:一個是 mCircleView(CircleImageView 實例,繼承自 ImageView,負責繪製進度圈背景);另一個是 mProgress(MaterialProgressDrawable 實例,繼承 Drawable 並實作 Animatable,負責繪製進度圈與動畫)。先看 moveSpinner:

 <span >private void moveSpinner(float overscrollTop) { mProgress.showArrow(true); float originalDragPercent = overscrollTop / mTotalDragDistance; float dragPercent = Math.min(1f, Math.abs(originalDragPercent)); float adjustedPercent = (float) Math.max(dragPercent - .4, 0) * 5 / 3; float extraOS = Math.abs(overscrollTop) - mTotalDragDistance; float slingshotDist = mUsingCustomStart ? mSpinnerFinalOffset - mOriginalOffsetTop : mSpinnerFinalOffset; float tensionSlingshotPercent = Math.max(0, Math.min(extraOS, slingshotDist * 2) / slingshotDist); float tensionPercent = (float) ((tensionSlingshotPercent / 4) - Math.pow( (tensionSlingshotPercent / 4), 2)) * 2f; float extraMove = (slingshotDist) * tensionPercent * 2; int targetY = mOriginalOffsetTop + (int) ((slingshotDist * dragPercent) + extraMove); // where 1.0f is a full circle if (mCircleView.getVisibility() != View.VISIBLE) { mCircleView.setVisibility(View.VISIBLE); } if (!mScale) { ViewCompat.setScaleX(mCircleView, 1f); ViewCompat.setScaleY(mCircleView, 1f); } if (mScale) { setAnimationProgress(Math.min(1f, overscrollTop / mTotalDragDistance)); } if (overscrollTop < mTotalDragDistance) { if (mProgress.getAlpha() > STARTING_PROGRESS_ALPHA && !isAnimationRunning(mAlphaStartAnimation)) { // Animate the alpha startProgressAlphaStartAnimation(); } } else { if (mProgress.getAlpha() < MAX_ALPHA && !isAnimationRunning(mAlphaMaxAnimation)) { // Animate the alpha startProgressAlphaMaxAnimation(); } } float strokeStart = adjustedPercent * .8f; mProgress.setStartEndTrim(0f, Math.min(MAX_PROGRESS_ANGLE, strokeStart)); mProgress.setArrowScale(Math.min(1f, adjustedPercent)); float rotation = (-0.25f + .4f * adjustedPercent + tensionPercent * 2) * .5f; mProgress.setProgressRotation(rotation); setTargetOffsetTopAndBottom(targetY - mCurrentTargetOffsetTop, true /* requires update */); }</span> 

中間那一大段主要是數學運算與進度圈樣式設定,目的在優化手感(例如剛開始移動時增長較快,超過刷新距離後增長趨緩)。倒數第二行呼叫 setProgressRotation 並傳入算好的 rotation,mProgress 便據此繪製進度圈,主要動畫就在這裡。最後一行 setTargetOffsetTopAndBottom 負責調整進度圈位置:

 <span >private void setTargetOffsetTopAndBottom(int offset, boolean requiresUpdate) { mCircleView.bringToFront(); mCircleView.offsetTopAndBottom(offset); mCurrentTargetOffsetTop = mCircleView.getTop(); if (requiresUpdate && android.os.Build.VERSION.SDK_INT < 11) { invalidate(); } }</span>

邏輯很單純:調整進度圈位置並記錄。最後看 finishSpinner:

 <span >private void finishSpinner(float overscrollTop) { if (overscrollTop > mTotalDragDistance) { setRefreshing(true, true /* notify */); } else { // cancel refresh mRefreshing = false; mProgress.setStartEndTrim(0f, 0f); Animation.AnimationListener listener = null; if (!mScale) { listener = new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { if (!mScale) { startScaleDownAnimation(null); } } @Override public void onAnimationRepeat(Animation animation) { } }; } animateOffsetToStartPosition(mCurrentTargetOffsetTop, listener); mProgress.showArrow(false); } }</span> 

當移動距離超過設定值,就執行 setRefreshing(true, true),內部會更新一些成員變量後呼叫 animateOffsetToCorrectPosition,把進度圈移動到頂部的正確位置;若未超過,則執行 animateOffsetToStartPosition 回到起始位置。一併看這兩個方法:

 <span >private void animateOffsetToCorrectPosition(int from, AnimationListener listener) { mFrom = from; mAnimateToCorrectPosition.reset(); mAnimateToCorrectPosition.setDuration(ANIMATE_TO_TRIGGER_DURATION); mAnimateToCorrectPosition.setInterpolator(mDecelerateInterpolator); if (listener != null) { mCircleView.setAnimationListener(listener); } mCircleView.clearAnimation(); mCircleView.startAnimation(mAnimateToCorrectPosition); } private void animateOffsetToStartPosition(int from, AnimationListener listener) { if (mScale) { // Scale the item back down startScaleDownReturnToStartAnimation(from, listener); } else { mFrom = from; mAnimateToStartPosition.reset(); mAnimateToStartPosition.setDuration(ANIMATE_TO_START_DURATION); mAnimateToStartPosition.setInterpolator(mDecelerateInterpolator); if (listener != null) { mCircleView.setAnimationListener(listener); } mCircleView.clearAnimation(); mCircleView.startAnimation(mAnimateToStartPosition); } }</span> 

兩者邏輯幾乎相同,最後都會呼叫 mCircleView 的 startAnimation,只是傳入值與監聽器不同。

若是要執行刷新,傳入值為頭部高度,監聽器為:

 <span >private Animation.AnimationListener mRefreshListener = new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationRepeat(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { if (mRefreshing) { // Make sure the progress view is fully visible mProgress.setAlpha(MAX_ALPHA); mProgress.start(); if (mNotify) { if (mListener != null) { mListener.onRefresh(); } } mCurrentTargetOffsetTop = mCircleView.getTop(); } else { reset(); } } };</span> 

動畫完成、進度圈移到頂部後,會執行 mProgress.start(),這就是刷新時轉圈圈的動畫。接著若 mListener 不為空,就呼叫 onRefresh——這個 mListener 正是 setOnRefreshListener 所設定的監聽器,刷新邏輯就在此完成。若是要回到初始位置,傳入值為初始高度,監聽器為:

 <span >listener = new Animation.AnimationListener() { @Override public void onAnimationStart(Animation animation) { } @Override public void onAnimationEnd(Animation animation) { if (!mScale) { startScaleDownAnimation(null); } } @Override public void onAnimationRepeat(Animation animation) { } };</span> 

回到初始位置後會執行 startScaleDownAnimation,也就是消失的動畫,至此整個刷新流程就結束了。

梳理完這一趟,可以發現 SwipeRefreshLayout 的客製性確實偏低,難免讓人懷疑 Google 是否刻意希望大家都採用統一樣式。市面上不少第三方下拉刷新控件的客製性更好、使用也不難,但有些人(比如我)就是偏好官方控件,不到最後一刻都不想引入第三方。下一篇將探討如何用 SwipeRefreshLayout 實現自訂樣式,有興趣可參考:https://www.jb51.net/article/89311.htm

以上就是本文的全部內容,希望對大家的學習有所幫助。

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