- 开发当中经常会遇到的产品需求,
recycleview自动滚动到某一个位置。具体场景可能是如下: - 页面初始化之后自动自动跳转到某一个位置
- 页面滚动之后要回到某一个位置
- 为了展示完全需要
recycleview做微小的位置偏移等
针对如上问题,我们先来看看recycleview都有什么方法提供给我们。
1public void scrollToPosition(int position) { 2 if (mLayoutSuppressed) { 3 return; 4 } 5 stopScroll(); 6 if (mLayout == null) { 7 Log.e(TAG, "Cannot scroll to position a LayoutManager set. " 8 + "Call setLayoutManager with a non-null argument."); 9 return; 10 } 11 mLayout.scrollToPosition(position); 12 awakenScrollBars(); 13 } 14
scrollToPosition(int position)方法,滑动到指定position的item的顶部。
1public void smoothScrollToPosition(int position) { 2 if (mLayoutSuppressed) { 3 return; 4 } 5 if (mLayout == null) { 6 Log.e(TAG, "Cannot smooth scroll without a LayoutManager set. " 7 + "Call setLayoutManager with a non-null argument."); 8 return; 9 } 10 mLayout.smoothScrollToPosition(this, mState, position); 11 } 12
smoothScrollToPosition(int position) 方法同上,但是会有平滑滑动的效果。
1public void scrollBy(int x, int y) { 2 if (mLayout == null) { 3 Log.e(TAG, "Cannot scroll without a LayoutManager set. " 4 + "Call setLayoutManager with a non-null argument."); 5 return; 6 } 7 if (mLayoutSuppressed) { 8 return; 9 } 10 final boolean canScrollHorizontal = mLayout.canScrollHorizontally(); 11 final boolean canScrollVertical = mLayout.canScrollVertically(); 12 if (canScrollHorizontal || canScrollVertical) { 13 scrollByInternal(canScrollHorizontal ? x : 0, canScrollVertical ? y : 0, null); 14 } 15 } 16
scrollBy(int x, int y)方法通过传入偏移量进行滑动。
1public void startSmoothScroll(SmoothScroller smoothScroller) { 2 if (mSmoothScroller != null && smoothScroller != mSmoothScroller 3 && mSmoothScroller.isRunning()) { 4 mSmoothScroller.stop(); 5 } 6 mSmoothScroller = smoothScroller; 7 mSmoothScroller.start(mRecyclerView, this); 8 } 9
startSmoothScroll(SmoothScroller smoothScroller)通过传入一个SmoothScroller来控制recycleview的移动。
针对题前所说的三种情况来说 这个需求会涉及到几种情况如下:
- 目标
item已经出现在屏幕当中的情况,这时候调用方法一,方法二是达不到recycleview进行位置的移动的。这时候可以选择调用方法三来达到我们要的效果。
1 val smoothScroller: RecyclerView.SmoothScroller = object : LinearSmoothScroller(mContext) { 2 override fun getVerticalSnapPreference(): Int { 3 return SNAP_TO_START 4 } 5 } 6 7 smoothScroller.targetPosition = CIRCLE_POSITION + 1 8 mVirtualLayoutManager.startSmoothScroll(smoothScroller) 9
当然方法四也可以达到我们所要的效果,这时候需要算出来的是我们目标item距离顶部所需的距离
1rv.addOnScrollListener(new RecyclerView.OnScrollListener() { 2 @Override 3 public void onScrolled(RecyclerView recyclerView, int dx, int dy) { 4 super.onScrolled(recyclerView, dx, dy); 5 ...... 6 int toTop = rv.getChildAt(n).getTop(); 7 rvProduct.scrollBy(0, top); 8 ...... 9 } 10}); 11
- 当目标
item如果说并没有出现在屏幕中时,方法一和方法二就可以达到我们需要的效果。
