RecyclerView之SnapHelper源碼分析

很久沒有寫Android控件了,正好最近項目有個自定義控件的需求,整理了下做個總結,主要是實現(xiàn)類似于抖音翻頁的效果,但是有有點不同,需要在底部漏出后面的view,這樣說可能不好理解,看下Demo,按頁滑動,后面的View有放大縮放的動畫,滑動速度過小時會有回到原位的效果,下滑也是按頁滑動的效果。

record.gif

有的小伙伴可能說這個用 SnapHelper就可以了,沒錯,翻頁是要結合這個,但是也不是純粹靠這個,因為底部需要漏出來后面的view,所以LayoutManager就不能簡單的使用LinearLayoutManager,需要去自定義LayoutManager,然后再自定義SnapHelper

如果把自定義LayoutManagerSnapHelper放在一篇里面會太長,所以我們今天主要分析SnapHelper

本文分析的源碼是基于recyclerview-v7-26.1.0

1.ScrollFling

這方面參考我的上篇分享:RecyclerView之Scroll和Fling

總結一下調用棧就是:

SnapHelper
onFling ---> snapFromFling 

上面得到最終位置targetPosition,把位置給RecyclerView.SmoothScroller, 然后就開始滑動了:

RecyclerView.SmoothScroller
start --> onAnimation

在滑動過程中如果targetPosition對應的targetView已經layout出來了,就會回調SnapHelper,然后計算得到到當前位置到targetView的距離dx,dy

SnapHelper
onTargetFound ---> calculateDistanceToFinalSnap

然后把距離dx,dy更新給RecyclerView.Action:

RecyclerView.Action
update --> runIfNecessary --> recyclerView.mViewFlinger.smoothScrollBy

最后調用RecyclerView.ViewFlinger, 然后又回到onAnimation

class ViewFlinger implements Runnable

        public void smoothScrollBy(int dx, int dy, int duration, Interpolator interpolator) {
            if (mInterpolator != interpolator) {
                mInterpolator = interpolator;
                mScroller = new OverScroller(getContext(), interpolator);
            }
            setScrollState(SCROLL_STATE_SETTLING);
            mLastFlingX = mLastFlingY = 0;
            mScroller.startScroll(0, 0, dx, dy, duration);
            postOnAnimation();
        }

2.SnapHelper源碼分析

上面其實已經接觸到部分的SnapHelper源碼, SnapHelper其實是一個抽象類,有三個抽象方法:

    /**
     * Override to provide a particular adapter target position for snapping.
     *
     * @param layoutManager the {@link RecyclerView.LayoutManager} associated with the attached
     *                      {@link RecyclerView}
     * @param velocityX fling velocity on the horizontal axis
     * @param velocityY fling velocity on the vertical axis
     *
     * @return the target adapter position to you want to snap or {@link RecyclerView#NO_POSITION}
     *         if no snapping should happen
     */
    public abstract int findTargetSnapPosition(LayoutManager layoutManager, int velocityX,
            int velocityY);

    /**
     * Override this method to snap to a particular point within the target view or the container
     * view on any axis.
     * <p>
     * This method is called when the {@link SnapHelper} has intercepted a fling and it needs
     * to know the exact distance required to scroll by in order to snap to the target view.
     *
     * @param layoutManager the {@link RecyclerView.LayoutManager} associated with the attached
     *                      {@link RecyclerView}
     * @param targetView the target view that is chosen as the view to snap
     *
     * @return the output coordinates the put the result into. out[0] is the distance
     * on horizontal axis and out[1] is the distance on vertical axis.
     */
    @SuppressWarnings("WeakerAccess")
    @Nullable
    public abstract int[] calculateDistanceToFinalSnap(@NonNull LayoutManager layoutManager,
            @NonNull View targetView);

    /**
     * Override this method to provide a particular target view for snapping.
     * <p>
     * This method is called when the {@link SnapHelper} is ready to start snapping and requires
     * a target view to snap to. It will be explicitly called when the scroll state becomes idle
     * after a scroll. It will also be called when the {@link SnapHelper} is preparing to snap
     * after a fling and requires a reference view from the current set of child views.
     * <p>
     * If this method returns {@code null}, SnapHelper will not snap to any view.
     *
     * @param layoutManager the {@link RecyclerView.LayoutManager} associated with the attached
     *                      {@link RecyclerView}
     *
     * @return the target view to which to snap on fling or end of scroll
     */
    @SuppressWarnings("WeakerAccess")
    @Nullable
    public abstract View findSnapView(LayoutManager layoutManager);

上面三個方法就是我們重寫SnapHelper需要實現(xiàn)的,很重要,簡單介紹下它們的作用和調用時機:

findTargetSnapPosition用來找到最終的目標位置,在fling操作剛觸發(fā)的時候會根據(jù)速度計算一個最終目標位置,然后開始fling操作
calculateDistanceToFinalSnap 這個用來計算滑動到最終位置還需要滑動的距離,在一開始attachToRecyclerView或者targetView layout的時候會調用
findSnapView用來找到上面的targetView,就是需要對其的view,在calculateDistanceToFinalSnap調用之前會調用該方法。

我們看下SnapHelper怎么用的,其實就一行代碼:

this.snapHelper.attachToRecyclerView(view);

SnapHelper正是通過該方法附著到RecyclerView上,從而實現(xiàn)輔助RecyclerView滾動對齊操作,那我們就從上面的attachToRecyclerView開始入手:

    public void attachToRecyclerView(@Nullable RecyclerView recyclerView)
            throws IllegalStateException {
        if (mRecyclerView == recyclerView) {
            return; // nothing to do
        }
        if (mRecyclerView != null) {
            destroyCallbacks();
        }
        mRecyclerView = recyclerView;
        if (mRecyclerView != null) {
            setupCallbacks();
            mGravityScroller = new Scroller(mRecyclerView.getContext(),
                    new DecelerateInterpolator());
            snapToTargetExistingView();
        }
    }

attachToRecyclerView()方法中會清掉SnapHelper之前保存的RecyclerView對象的回調(如果有的話),對新設置進來的RecyclerView對象設置回調,然后初始化一個Scroller對象,最后調用snapToTargetExistingView()方法對SnapView進行對齊調整。

snapToTargetExistingView()

該方法的作用是對SnapView進行滾動調整,以使得SnapView達到對齊效果。

看下源碼:

    void snapToTargetExistingView() {
        if (mRecyclerView == null) {
            return;
        }
        LayoutManager layoutManager = mRecyclerView.getLayoutManager();
        if (layoutManager == null) {
            return;
        }
        View snapView = findSnapView(layoutManager);
        if (snapView == null) {
            return;
        }
        int[] snapDistance = calculateDistanceToFinalSnap(layoutManager, snapView);
        if (snapDistance[0] != 0 || snapDistance[1] != 0) {
            mRecyclerView.smoothScrollBy(snapDistance[0], snapDistance[1]);
        }
    }

snapToTargetExistingView()方法就是先找到SnapView,然后計算SnapView當前坐標到目的坐標之間的距離,然后調用RecyclerView.smoothScrollBy()方法實現(xiàn)對RecyclerView內容的平滑滾動,從而將SnapView移到目標位置,達到對齊效果。

其實這個時候RecyclerView還沒進行l(wèi)ayout,一般findSnapView會返回null,不需要對齊。

回調

SnapHelper要有對齊功能,肯定需要知道RecyclerView的滾動scroll和fling過程的,這個就是通過回調接口實現(xiàn)。再看下attachToRecyclerView的源碼:

    public void attachToRecyclerView(@Nullable RecyclerView recyclerView)
            throws IllegalStateException {
        if (mRecyclerView == recyclerView) {
            return; // nothing to do
        }
        if (mRecyclerView != null) {
            destroyCallbacks();
        }
        mRecyclerView = recyclerView;
        if (mRecyclerView != null) {
            setupCallbacks();
            mGravityScroller = new Scroller(mRecyclerView.getContext(),
                    new DecelerateInterpolator());
            snapToTargetExistingView();
        }
    }

一開始會先清空之前的回調接口然后再注冊接口,先看下destroyCallbacks:

    /**
     * Called when the instance of a {@link RecyclerView} is detached.
     */
    private void destroyCallbacks() {
        mRecyclerView.removeOnScrollListener(mScrollListener);
        mRecyclerView.setOnFlingListener(null);
    }

可以看出SnapHelperRecyclerView設置了兩個回調,一個是OnScrollListener對象mScrollListener,另外一個就是OnFlingListener對象。

再看下setupCallbacks:

    /**
     * Called when an instance of a {@link RecyclerView} is attached.
     */
    private void setupCallbacks() throws IllegalStateException {
        if (mRecyclerView.getOnFlingListener() != null) {
            throw new IllegalStateException("An instance of OnFlingListener already set.");
        }
        mRecyclerView.addOnScrollListener(mScrollListener);
        mRecyclerView.setOnFlingListener(this);
    }

SnapHelper實現(xiàn)了RecyclerView.OnFlingListener接口,所以OnFlingListener就是SnapHelper自身。

先來看下RecyclerView.OnScrollListener對象mScrollListener

RecyclerView.OnScrollListener

先看下mScrollListener是怎么實現(xiàn)的:

    private final RecyclerView.OnScrollListener mScrollListener =
            new RecyclerView.OnScrollListener() {
                boolean mScrolled = false;

                @Override
                public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                    super.onScrollStateChanged(recyclerView, newState);
                    if (newState == RecyclerView.SCROLL_STATE_IDLE && mScrolled) {
                        mScrolled = false;
                        snapToTargetExistingView();
                    }
                }

                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    if (dx != 0 || dy != 0) {
                        mScrolled = true;
                    }
                }
            };

mScrolled = true表示之前滾動過,RecyclerView.SCROLL_STATE_IDLE表示滾動停止,這個不清楚的可以看考之前的博客RecyclerView之Scroll和Fling。這個監(jiān)聽器的實現(xiàn)其實很簡單,就是在滾動停止的時候調用snapToTargetExistingView對目標View進行滾動調整對齊。

RecyclerView.OnFlingListener

RecyclerView.OnFlingListener接口只有一個方法,這個就是在Fling操作觸發(fā)的時候會回調,返回true就是已處理,返回false就會交給系統(tǒng)處理。

    /**
     * This class defines the behavior of fling if the developer wishes to handle it.
     * <p>
     * Subclasses of {@link OnFlingListener} can be used to implement custom fling behavior.
     *
     * @see #setOnFlingListener(OnFlingListener)
     */
    public abstract static class OnFlingListener {

        /**
         * Override this to handle a fling given the velocities in both x and y directions.
         * Note that this method will only be called if the associated {@link LayoutManager}
         * supports scrolling and the fling is not handled by nested scrolls first.
         *
         * @param velocityX the fling velocity on the X axis
         * @param velocityY the fling velocity on the Y axis
         *
         * @return true if the fling was handled, false otherwise.
         */
        public abstract boolean onFling(int velocityX, int velocityY);
    }

看下SnapHelper怎么實現(xiàn)onFling()方法:

    @Override
    public boolean onFling(int velocityX, int velocityY) {
        LayoutManager layoutManager = mRecyclerView.getLayoutManager();
        if (layoutManager == null) {
            return false;
        }
        RecyclerView.Adapter adapter = mRecyclerView.getAdapter();
        if (adapter == null) {
            return false;
        }
        int minFlingVelocity = mRecyclerView.getMinFlingVelocity();
        return (Math.abs(velocityY) > minFlingVelocity || Math.abs(velocityX) > minFlingVelocity)
                && snapFromFling(layoutManager, velocityX, velocityY);
    }

首先會獲取mRecyclerView.getMinFlingVelocity()需要進行fling操作的最小速率,只有超過該速率,Item才能在手指離開的時候進行Fling操作。
關鍵就是調用snapFromFling方法實現(xiàn)平滑滾動。

snapFromFling

看下怎么實現(xiàn)的:

    private boolean snapFromFling(@NonNull LayoutManager layoutManager, int velocityX,
            int velocityY) {
        if (!(layoutManager instanceof ScrollVectorProvider)) {
            return false;
        }

        SmoothScroller smoothScroller = createScroller(layoutManager);
        if (smoothScroller == null) {
            return false;
        }

        int targetPosition = findTargetSnapPosition(layoutManager, velocityX, velocityY);
        if (targetPosition == RecyclerView.NO_POSITION) {
            return false;
        }

        smoothScroller.setTargetPosition(targetPosition);
        layoutManager.startSmoothScroll(smoothScroller);
        return true;
    }
  1. 首先判斷是不是實現(xiàn)了ScrollVectorProvider接口,系統(tǒng)提供的Layoutmanager默認都實現(xiàn)了該接口
  2. 創(chuàng)建SmoothScroller對象,默認是LinearSmoothScroller對象,會用LinearInterpolator進行平滑滾動,在目標位置成為Recyclerview的子View時會用DecelerateInterpolator進行減速停止。
  3. 通過findTargetSnapPosition()方法,以layoutManager和速率作為參數(shù),找到targetSnapPosition,這個方法就是自定義SnapHelper需要實現(xiàn)的。
  4. 把targetSnapPosition設置給平滑滾動器,然后開始進行滾動操作。

很明顯重點就是要看下平滑滾動器了。

LinearSmoothScroller

看下系統(tǒng)怎么實現(xiàn):

    @Nullable
    protected LinearSmoothScroller createSnapScroller(LayoutManager layoutManager) {
        if (!(layoutManager instanceof ScrollVectorProvider)) {
            return null;
        }
        return new LinearSmoothScroller(mRecyclerView.getContext()) {
            @Override
            protected void onTargetFound(View targetView, RecyclerView.State state, Action action) {
                int[] snapDistances = calculateDistanceToFinalSnap(mRecyclerView.getLayoutManager(),
                        targetView);
                final int dx = snapDistances[0];
                final int dy = snapDistances[1];
                final int time = calculateTimeForDeceleration(Math.max(Math.abs(dx), Math.abs(dy)));
                if (time > 0) {
                    action.update(dx, dy, time, mDecelerateInterpolator);
                }
            }

            @Override
            protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
                return MILLISECONDS_PER_INCH / displayMetrics.densityDpi;
            }
        };
    }

在通過findTargetSnapPosition()方法找到的targetSnapPosition成為Recyclerview的子View時(根據(jù)Recyclerview的緩存機制,這個時候可能該View在屏幕上還看不到),會回調onTargetFound,看下系統(tǒng)定義:

        /**
         * Called when the target position is laid out. This is the last callback SmoothScroller
         * will receive and it should update the provided {@link Action} to define the scroll
         * details towards the target view.
         * @param targetView    The view element which render the target position.
         * @param state         Transient state of RecyclerView
         * @param action        Action instance that you should update to define final scroll action
         *                      towards the targetView
         */
        protected abstract void onTargetFound(View targetView, State state, Action action);

傳入的第一個參數(shù)targetView就是我們希望滾動到的位置對應的View,最后一個參數(shù)就是我們可以用來通知滾動器要減速滾動的距離。

其實就是我們要在這個方法里面告訴滾動器在目標子View layout出來后還需要滾動多少距離, 然后通過Action通知滾動器。

第二個方法是計算滾動速率,返回值會影響onTargetFound中的calculateTimeForDeceleration方法,看下源碼:

    private final float MILLISECONDS_PER_PX;
    public LinearSmoothScroller(Context context) {
        MILLISECONDS_PER_PX = calculateSpeedPerPixel(context.getResources().getDisplayMetrics());
    }

    /**
     * Calculates the time it should take to scroll the given distance (in pixels)
     *
     * @param dx Distance in pixels that we want to scroll
     * @return Time in milliseconds
     * @see #calculateSpeedPerPixel(android.util.DisplayMetrics)
     */
    protected int calculateTimeForScrolling(int dx) {
        // In a case where dx is very small, rounding may return 0 although dx > 0.
        // To avoid that issue, ceil the result so that if dx > 0, we'll always return positive
        // time.
        return (int) Math.ceil(Math.abs(dx) * MILLISECONDS_PER_PX);
    }

    /**
     * <p>Calculates the time for deceleration so that transition from LinearInterpolator to
     * DecelerateInterpolator looks smooth.</p>
     *
     * @param dx Distance to scroll
     * @return Time for DecelerateInterpolator to smoothly traverse the distance when transitioning
     * from LinearInterpolation
     */
    protected int calculateTimeForDeceleration(int dx) {
        // we want to cover same area with the linear interpolator for the first 10% of the
        // interpolation. After that, deceleration will take control.
        // area under curve (1-(1-x)^2) can be calculated as (1 - x/3) * x * x
        // which gives 0.100028 when x = .3356
        // this is why we divide linear scrolling time with .3356
        return  (int) Math.ceil(calculateTimeForScrolling(dx) / .3356);
    }

可以看到,第二個方法返回值越大,需要滾動的時間越長,也就是滾動越慢。

3.總結

到這里,SnapHelper的源碼就分析完了,整理下思路,SnapHelper輔助RecyclerView實現(xiàn)滾動對齊就是通過給RecyclerView設置OnScrollerListenerOnFlingListener這兩個監(jiān)聽器實現(xiàn)的。
整個過程如下:

  1. onFling操作觸發(fā)的時候首先通過findTargetSnapPosition找到最終需要滾動到的位置,然后啟動平滑滾動器滾動到指定位置,
  2. 在指定位置需要渲染的View -targetView layout出來后,系統(tǒng)會回調onTargetFound,然后調用calculateDistanceToFinalSnap方法計算targetView需要減速滾動的距離,然后通過Action更新給滾動器。
  3. 在滾動停止的時候,也就是state變成SCROLL_STATE_IDLE時會調用snapToTargetExistingView,通過findSnapView找到SnapView,然后通過calculateDistanceToFinalSnap計算得到滾動的距離,做最后的對齊調整。

前面分享的Demo就留到下一篇博客再說了,其實只要理解了SnapHelper的源碼,自定義就很簡單了。

對Demo感興趣的歡迎關注下一篇博客了。

完。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,563評論 6 544
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 99,694評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,672評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,965評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,690評論 6 413
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 56,019評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,013評論 3 449
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,188評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經...
    沈念sama閱讀 49,718評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,438評論 3 360
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,667評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,149評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,845評論 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,252評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,590評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,384評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,635評論 2 380

推薦閱讀更多精彩內容