1. 程式人生 > >Android8.0對於CoordinatorLayout、RecyclerView 精準fling的優化

Android8.0對於CoordinatorLayout、RecyclerView 精準fling的優化

之前為了開發需求,學習了NestedScrolling機制,並使用CoordinatorLayout、AppBarLayout、RecyclerView配合實現了相關的效果,還寫了一篇關於分析原理的文章關於CoordinatorLayout AppBarLayout原理的一些分析,當時做完需求以後,內心其實是一隻有種遺憾的,因為在使用RecyclerView時,對於向上滑動的fling效果其實是有問題的,滑動起來的感覺並不是連貫的,可以看一下這個效果:
old.gif

這個效果的體驗其實並不是太好,因為向下fling時我們希望的效果是父佈局可以在RecyclerView到達頂部時,如果沒有消耗完fling時可以由父佈局消耗從而繼續滑動的,可是由於之前的實現方式,並沒有辦法用常規的辦法達到這一點,Google也意識到了這個問題,所以在Android 8.0 擴充套件了NestedScrolling的相關介面,使得滑動可以變得更加順暢了,效果如下,簡直如絲般順滑:
new.gif


在分析相關的原理之前,如果你們急需解決專案中的這種滑動不順暢,可以先把解決方法告訴大家,那就是把compileSdkVersion升到26然後使用26.1.0的相關控制元件

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    buildToolsVersion '26.0.2'
    .......
}

dependencies {
 ....
    compile 'com.android.support:recyclerview-v7:26.1.0'
    compile 'com.android.support:support-v4:26+'
compile 'com.android.support:design:26.1.0' ..... }

這樣改好之後,不需要改動一行程式碼,即可完美實現如絲般順滑的fling。

問題發生的原因

RecyclerView中,fling的呼叫發生在滑動事件MotionEvent.ACTION_UP時,在25+版本之前RecycleView只是在fling的開始之前通知了Parent是否消耗fling以及將fling分發到parent,這隻能做到Parent和RecyclerView同時fling或者Parent自己fling,在RecyclerView的fling過程中並沒有通知Parent,在RecyclerView fling結束之後,Parent不能拿到剩餘未消耗的距離,所以導致了這個不能連貫滑動的問題,25+版本的RecyclerView的fling方法如下:

public boolean fling(int velocityX, int velocityY) {
    if (mLayout == null) {
        Log.e(TAG, "Cannot fling without a LayoutManager set. " +
                "Call setLayoutManager with a non-null argument.");
        return false;
    }
    if (mLayoutFrozen) {
        return false;
    }

    final boolean canScrollHorizontal = mLayout.canScrollHorizontally();
    final boolean canScrollVertical = mLayout.canScrollVertically();

    if (!canScrollHorizontal || Math.abs(velocityX) < mMinFlingVelocity) {
        velocityX = 0;
    }
    if (!canScrollVertical || Math.abs(velocityY) < mMinFlingVelocity) {
        velocityY = 0;
    }
    if (velocityX == 0 && velocityY == 0) {
        // If we don't have any velocity, return false
        return false;
    }

    if (!dispatchNestedPreFling(velocityX, velocityY)) {
        final boolean canScroll = canScrollHorizontal || canScrollVertical;
        dispatchNestedFling(velocityX, velocityY, canScroll);

        if (mOnFlingListener != null && mOnFlingListener.onFling(velocityX, velocityY)) {
            return true;
        }

        if (canScroll) {
            velocityX = Math.max(-mMaxFlingVelocity, Math.min(velocityX, mMaxFlingVelocity));
            velocityY = Math.max(-mMaxFlingVelocity, Math.min(velocityY, mMaxFlingVelocity));
            mViewFlinger.fling(velocityX, velocityY);
            return true;
        }
    }
    return false;
}

後面的程式碼我就不貼了,給大家放一張時序圖,表明RecyclerView的dispatchNestedPreFling和dispatchNestedFling是如何到達AppBarLayout的
時序圖1.png
可以看到,一旦fling事件開始之後,大家就各玩各的了。

網上的一些解決辦法

我在之前做需求時,就對這個不能流暢滑動感覺特別無奈,本想著問題找到了,那我就把一些類繼承一下重新實現一些方法唄,然後發現了基本上用到的類都是在design包下不對外開放的,頓時發現後路被堵死,前幾天在簡書上看到一個人實現的效果不錯,他把所有相關的類都拷出來並且做了一些修改,我感覺思路挺不錯的,文章的地址是支付寶首頁互動三部曲 3 實現支付寶首頁互動,可以看看他文章裡面的github上的程式碼實現的效果,很不錯。
當然我當時並沒有像他這樣解決這個問題,我在StackOverFlow看到了一個辦法,這個方法可以保證RecyclerView在向下fling時,如果第一個元素的位置不超過我們設定的閥值,那麼我們就可以讓AppBarLayout和RecyclerView一起fling,實現效果其實相對於不做處理會好很多,主要就是覆寫AppBarLayout.Behavior

public final class FlingBehavior extends AppBarLayout.Behavior {
    private static final int TOP_CHILD_FLING_THRESHOLD = 3;
    private boolean isPositive;

    public FlingBehavior() {
    }

    public FlingBehavior(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onNestedFling(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, float velocityX, float velocityY, boolean consumed) {
        if (velocityY > 0 && !isPositive || velocityY < 0 && isPositive) {
            velocityY = velocityY * -1;
        }
        //判斷是否上滑,並且第一個元素是否在閥值內
        if (target instanceof RecyclerView && velocityY < 0) {
            final RecyclerView recyclerView = (RecyclerView) target;
            final View firstChild = recyclerView.getChildAt(0);
            final int childAdapterPosition = recyclerView.getChildAdapterPosition(firstChild);
            consumed = childAdapterPosition > TOP_CHILD_FLING_THRESHOLD;
        }
        return super.onNestedFling(coordinatorLayout, child, target, velocityX, velocityY, consumed);
    }

    @Override
    public void onNestedPreScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child, View target, int dx, int dy, int[] consumed) {
        super.onNestedPreScroll(coordinatorLayout, child, target, dx, dy, consumed);
        isPositive = dy > 0;
    }
}

這樣寫好之後會比之前流暢很多

Android8.0的改變

Google也許也認識到了這個問題,可能反饋這個問題的人太多了吧,終於在Android8.0的版本里解決掉了這個問題,這個問題讓他們來解決其實最合理,因為很多類都是不對外開放的,開發者如果自己解決肯定要把很多類自己考出來一份在修改一下,造成了不必要的浪費。
Google的解決辦法還是挺厲害的,他們並沒有頭疼治頭,而是把整個問題抽象出來,升級了NestedScrolling相關的介面,現在使用的都是NestedScrollingParent2和NestedScrollingChild2介面,用NestedScrollType來區分是touch觸發的滑動還是非touch觸發的滑動,例如NestedScrollingChild2繼承自NestedScrollingChild定義如下:

public interface NestedScrollingChild2 extends NestedScrollingChild {

    boolean startNestedScroll(@ScrollAxis int axes, @NestedScrollType int type);


    void stopNestedScroll(@NestedScrollType int type);


    boolean hasNestedScrollingParent(@NestedScrollType int type);


    boolean dispatchNestedScroll(int dxConsumed, int dyConsumed,
            int dxUnconsumed, int dyUnconsumed, @Nullable int[] offsetInWindow,
            @NestedScrollType int type);

    boolean dispatchNestedPreScroll(int dx, int dy, @Nullable int[] consumed,
            @Nullable int[] offsetInWindow, @NestedScrollType int type);
}

可以發現CoordinatorLayout、RecyclerView目前實現的介面不在是NestedScrollingParent和NestedScrollingChild,而是NestedScrollingParent2和NestedScrollingChild2。
解決這個問題的主要辦法就是要在RecyclerView的整個fling過程中通知到Parent進行一些處理,首先會在fling開始之前通知Parent做記錄,然後在每次fling之前先通知Parent進行消耗,在自己每次fling之後如果有剩餘沒有消耗的距離,在繼續傳遞給Parent,先看一下RecyclerView在改變前後的對比:
RecyclerView對比.png
然後ViewFlinger的執行方法中也作出了改變,在每次fling滑動之前會通知到Parent,在滑動結束之後會把剩餘未消耗傳遞到Parent,也是解決這個問題的關鍵,對比如下:
ViewFlinger對比.png

ViewFlinger對比2.png

整個過程的分析

上面主要對8.0版本和之前版本的實現差別做了對比,現在通過對整個流程的分析,來解釋Google時如何解決這個問題的,接著上面RecyclerView在fling開始的時候呼叫startNestedScroll方法開始,我們可以根據原始碼畫出如下的流程圖:
fling過程.png
這裡涉及到的整個原始碼有點略多,所以大家可以根據流程圖的過程去檢視相應的原始碼,這裡主要把這些過程分成幾個組,然後只要看最關鍵的程式碼就可以了。
- 第一組:流程圖中的1-9過程
這個過程主要是在RecyclerView fling之前,記錄一下ParentView,這個ParentView的type是TYPE_NON_TOUCH的,這樣在接下來的處理過程當中,我們所有相關的ParentView都是在這裡記錄下來的View,如果此時ParentView不做處理,那麼後續的操作都不回傳遞到ParentView當中,這個之前的NestedScrolling的方法的意思是一樣的,只不過這裡多了一個type。NestedScrollingChildHelper對應原始碼如下:

public boolean startNestedScroll(@ScrollAxis int axes, @NestedScrollType int type) {
    if (hasNestedScrollingParent(type)) {
        // Already in progress
        return true;
    }
    if (isNestedScrollingEnabled()) {
        ViewParent p = mView.getParent();
        View child = mView;
        while (p != null) {
            if (ViewParentCompat.onStartNestedScroll(p, child, mView, axes, type)) {
                setNestedScrollingParentForType(type, p);
                ViewParentCompat.onNestedScrollAccepted(p, child, mView, axes, type);
                return true;
            }
            if (p instanceof View) {
                child = (View) p;
            }
            p = p.getParent();
        }
    }
    return false;
}
  • 第二組:流程圖中的10-13過程
    這裡的思想就是NestScrolling的核心思想,在我未消耗之前,先傳遞給ParentView做消耗,我消耗剩餘的部分,RecyclerView.ViewFlinger相關原始碼如下:
public void run() {
    if (mLayout == null) {
        stop();
        return; // no layout, cannot scroll.
    }
    disableRunOnAnimationRequests();
    consumePendingUpdateOperations();
    // keep a local reference so that if it is changed during onAnimation method, it won't
    // cause unexpected behaviors
    final OverScroller scroller = mScroller;
    final SmoothScroller smoothScroller = mLayout.mSmoothScroller;
    if (scroller.computeScrollOffset()) {
        final int[] scrollConsumed = mScrollConsumed;
        final int x = scroller.getCurrX();
        final int y = scroller.getCurrY();
        int dx = x - mLastFlingX;
        int dy = y - mLastFlingY;
        int hresult = 0;
        int vresult = 0;
        mLastFlingX = x;
        mLastFlingY = y;
        int overscrollX = 0, overscrollY = 0;
        //在這裡傳遞
        if (dispatchNestedPreScroll(dx, dy, scrollConsumed, null, TYPE_NON_TOUCH)) {
            dx -= scrollConsumed[0];
            dy -= scrollConsumed[1];
        }
        ..................
    }
}

NestedScrollingChildHelper的dispatchNestedPreScroll如下:

public boolean dispatchNestedPreScroll(int dx, int dy, @Nullable int[] consumed,
        @Nullable int[] offsetInWindow, @NestedScrollType int type) {
    if (isNestedScrollingEnabled()) {
        //如果對應的type沒有記錄下來,那麼不做處理直接返回false
        final ViewParent parent = getNestedScrollingParentForType(type);
        if (parent == null) {
            return false;
        }

        if (dx != 0 || dy != 0) {
            int startX = 0;
            int startY = 0;
            if (offsetInWindow != null) {
                mView.getLocationInWindow(offsetInWindow);
                startX = offsetInWindow[0];
                startY = offsetInWindow[1];
            }

            if (consumed == null) {
                if (mTempNestedScrollConsumed == null) {
                    mTempNestedScrollConsumed = new int[2];
                }
                consumed = mTempNestedScrollConsumed;
            }
            consumed[0] = 0;
            consumed[1] = 0;
            ViewParentCompat.onNestedPreScroll(parent, mView, dx, dy, consumed, type);

            if (offsetInWindow != null) {
                mView.getLocationInWindow(offsetInWindow);
                offsetInWindow[0] -= startX;
                offsetInWindow[1] -= startY;
            }
            return consumed[0] != 0 || consumed[1] != 0;
        } else if (offsetInWindow != null) {
            offsetInWindow[0] = 0;
            offsetInWindow[1] = 0;
        }
    }
    return false;
}
  • 第三組: 流程圖中的14-18過程
    這個過程,就是解決之前不能夠準確fling的關鍵步驟,因為之前的ViewFlinger對於沒有消耗完的距離只是判斷了除了自己消耗完以外,剩下的不是0那麼就會做一些清除動畫之類的操作,所以並沒有給ParentView一個繼續滑動的機會,這次除了判斷不等於0的條件外,還要把剩餘的距離傳遞給ParentView,給ParentView一個準確Fling的機會,ViewFlinger的dispatchNestedScroll方法會呼叫到NestedScrollingChildHelper的dispatchNestedScroll方法,然後根據流程圖的順序,一直呼叫到AppBarLayout的onNestedScroll方法,我們可以看一下AppBarLayout的onNestedScroll就會覺得恍然大悟:
public void onNestedScroll(CoordinatorLayout coordinatorLayout, AppBarLayout child,
        View target, int dxConsumed, int dyConsumed, int dxUnconsumed, int dyUnconsumed,
        int type) {
    if (dyUnconsumed < 0) {
        // If the scrolling view is scrolling down but not consuming, it's probably be at
        // the top of it's content
        scroll(coordinatorLayout, child, dyUnconsumed,
                -child.getDownNestedScrollRange(), 0);
    }
}

這裡只做了一件事兒,翻譯一下注釋的意思就是,“dyUnconsumed<0的時候,說明View的內容正在向下滑動,並且沒有消耗完滑動事件,可能是View已經到達了內容的頂部”,所以在出現了這種情況的時候,AppBarLayout回撥用自己的scroll方法來繼續消耗,從而達到了精準fling的目的。

整個流程就分析完了,看了這塊的原始碼,感覺對這部分的內容理解又加深了一下,希望以後能有時間在多看看其他的原始碼,看原始碼的收穫還是挺大的~