RecyclerView 滑動控制筆記

為了將指定的 item 平滑的滑動至置頂。

  • 簡單的直接置頂:
mLayoutManager.scrollToPositionWithOffset(position, 0);//沒有滑動,直接置頂

缺點是體驗不好,沒有滑動的過程。

  • RecyclerView 的滑動方法
rv.scrollToPosition(index);//直接定位,沒有滑動的過程,不能置頂
rv.smoothScrollToPosition(position);//平滑的滑動,不能置頂
rv.scrollBy(int x, int y);

scrollToPosition();smoothScrollToPosition() 將對應的 item 滑動到屏幕內,當 item 變為可見時則停止滑動。
所以當指定的 item 在當前屏幕的下方時,滑動后目標 item 會出現屏幕的最底部;
當指定 item 在屏幕可見時,則完全沒有滑動。
很多時候這個方法是不符合我們預期的,有時候,我們希望能將指定的 item 平滑的滑動到當前的屏幕頂端或中間。
這時候可以配合 scrollBy() 來做一個判斷:

private void setSelectPosition(int index) {
    //當前可見的第一項和最后一項
    int firstItem = linearLayoutManager.findFirstVisibleItemPosition();
    int lastItem = linearLayoutManager.findLastVisibleItemPosition();
    if (index <= firstItem) {
        //當要置頂的項在當前顯示的第一個項的前面時,直接調用沒有問題
        rv.scrollToPosition(index);
    } else if (index <= lastItem) {
        //當要置頂的項已經在屏幕上顯示時,計算需要滑動的距離
        int top = rv.getChildAt(index - firstItem).getTop();
        rv.scrollBy(0, top);
    } else {
        //當指定的 item 在當前顯示的最后一項的后面時
        //這時候一次的滑動不足以將指定 item 放到頂端
        rv.scrollToPosition(index);
        //記錄當前需要在RecyclerView滾動監聽里面繼續第二次滾動
        move = true;
    }
}
//在第三種的情況中,scrollToPosition() 結束后該方法被調用
class RecyclerViewListener extends RecyclerView.OnScrollListener{
        @Override
        public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
            super.onScrolled(recyclerView, dx, dy);
            //在這里進行第二次滾動
            if (move ){
                move = false;
                int n = mIndex - mLinearLayoutManager.findFirstVisibleItemPosition();
                if ( 0 <= n && n < mRecyclerView.getChildCount()){
                    //要移動的距離
                    int top = mRecyclerView.getChildAt(n).getTop();
                    mRecyclerView.scrollBy(0, top);
                }
            }
        }
    }

上面這個方面也是看到別人的實現的思路,雖然沒什么問題不過還是算是取巧的一種方法,僅記錄。

其實 Stack Overflow 上已經有了更好的答案 :RecyclerView - How to smooth scroll to top of item on a certain position?

  • 重寫 LinearLayoutManager
public class LinearLayoutManagerWithSmoothScroller extends LinearLayoutManager {

    public LinearLayoutManagerWithSmoothScroller(Context context) {
        super(context, VERTICAL, false);
    }

    public LinearLayoutManagerWithSmoothScroller(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    //重點方法
    @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state,
                                       int position) {

        //也就是說重點在于重寫 SmoothScroller,而滑動的調用為 startSmoothScroll()
        RecyclerView.SmoothScroller smoothScroller = new  TopSnappedSmoothScroller(recyclerView.getContext());
        smoothScroller.setTargetPosition(position);
        startSmoothScroll(smoothScroller);
    }

    private class TopSnappedSmoothScroller extends LinearSmoothScroller {
        public TopSnappedSmoothScroller(Context context) {
            super(context);
        }

        @Override
        public PointF computeScrollVectorForPosition(int targetPosition) {
            return LinearLayoutManagerWithSmoothScroller.this
                    .computeScrollVectorForPosition(targetPosition);
        }

        @Override
        protected int getVerticalSnapPreference() {
            //將指定的 item 滑動至與屏幕的頂端對齊
            return SNAP_TO_START;
        }
    }
}

//使用
recyclerView.smoothScrollToPosition(position);

仔細看可以發現我們也可以選擇不重寫整個 LinearLayoutManager,只要將 LinearSmoothScroller 的 getVerticalSnapPreference() 重寫也可以達到目的。

關于 getVerticalSnapPreference () 的源碼與注釋:

    /**
     * When scrolling towards a child view, this method defines whether we should align the top
     * or the bottom edge of the child with the parent RecyclerView.
     *
     * @return SNAP_TO_START, SNAP_TO_END or SNAP_TO_ANY; depending on the current target vector
     * @see #SNAP_TO_START
     * @see #SNAP_TO_END
     * @see #SNAP_TO_ANY
     */
    protected int getVerticalSnapPreference() {
        return mTargetVector == null || mTargetVector.y == 0 ? SNAP_TO_ANY :
                mTargetVector.y > 0 ? SNAP_TO_END : SNAP_TO_START;
    }

返回的值決定了指定 item 的對齊方式,與頂部對齊 / 底部對齊。
所以最終代碼:

//初始化過程
mLayoutManager= new LinearLayoutManager(getActivity());
mSmoothScroller = new LinearSmoothScroller(getActivity()) {
    @Override protected int getVerticalSnapPreference() {
        return LinearSmoothScroller.SNAP_TO_START;
     }

    @Override
    public PointF computeScrollVectorForPosition(int targetPosition) {
        return mLayoutManager.computeScrollVectorForPosition(targetPosition);
    }
};
mRvRetail.setLayoutManager(mLayoutManager);

//滑動
mSmoothScroller.setTargetPosition(position);
mLayoutManager.startSmoothScroll(mSmoothScroller);
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容