RecyclerView - 如何平滑滚动到特定位置的项目顶部?

RecyclerView - How to smooth scroll to top of item on a certain position?

在 RecyclerView 上,我可以使用以下方法突然滚动到所选项目的顶部:

((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(position, 0);

但是,这突然将项目移动到顶部位置。我想平滑地移动到项目的顶部

我也试过:

recyclerView.smoothScrollToPosition(position);

但效果不佳,因为它不会将项目移动到顶部选定的位置。它只是滚动列表,直到该位置上的项目可见。

为此您必须创建一个自定义 LayoutManager

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) {
        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() {
            return SNAP_TO_START;
        }
    }
}

将它用于您的 RecyclerView 并调用 smoothScrollToPosition。

示例:

 recyclerView.setLayoutManager(new LinearLayoutManagerWithSmoothScroller(context));
 recyclerView.smoothScrollToPosition(position);

这将滚动到指定位置的 RecyclerView 项目的顶部。

希望这对您有所帮助。

RecyclerView 被设计成可扩展的,所以不需要为了执行滚动而继承 LayoutManager(如 )。

相反,只需创建一个 SmoothScroller,首选项为 SNAP_TO_START:

RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(context) {
  @Override protected int getVerticalSnapPreference() {
    return LinearSmoothScroller.SNAP_TO_START;
  }
};

现在您设置要滚动到的位置:

smoothScroller.setTargetPosition(position);

并将 SmoothScroller 传递给 LayoutManager:

layoutManager.startSmoothScroll(smoothScroller);

我发现滚动 RecyclerView 的最简单方法如下:

// Define the Index we wish to scroll to.
final int lIndex = 0;
// Assign the RecyclerView's LayoutManager.
this.getRecyclerView().setLayoutManager(this.getLinearLayoutManager());
// Scroll the RecyclerView to the Index.
this.getLinearLayoutManager().smoothScrollToPosition(this.getRecyclerView(), new RecyclerView.State(), lIndex);

我们可以这样试试

    recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView,new RecyclerView.State(), recyclerView.getAdapter().getItemCount());

可能 @droidev 的方法是正确的,但我只想发布一些稍微不同的东西,它的工作基本相同,不需要扩展 LayoutManager。

注意 - 如果您的项目(您想要滚动到列表顶部的项目)在屏幕上可见并且您只是想自动滚动到顶部。当列表中的最后一项有一些操作时,它很有用,它会在同一列表中添加新项目,并且您希望将用户的注意力集中在新添加的项目上:

int recyclerViewTop = recyclerView.getTop();
int positionTop = recyclerView.findViewHolderForAdapterPosition(positionToScroll) != null ? recyclerView.findViewHolderForAdapterPosition(positionToScroll).itemView.getTop() : 200;
final int calcOffset = positionTop - recyclerViewTop; 
//then the actual scroll is gonna happen with (x offset = 0) and (y offset = calcOffset)
recyclerView.scrollBy(0, offset);

想法很简单: 1、我们需要获取recyclerview元素的top坐标; 2、我们需要获取到我们想要滚动到顶部的view item的top坐标; 3. 在计算出偏移量的最后,我们需要做

recyclerView.scrollBy(0, offset);

200 只是示例硬编码整数值,如果查看器项目不存在,您可以使用它,因为这也是可能的。

覆盖LinearSmoothScroller中的calculateDyToMakeVisible/calculateDxToMakeVisible函数实现偏移Y/X位置

override fun calculateDyToMakeVisible(view: View, snapPreference: Int): Int {
    return super.calculateDyToMakeVisible(view, snapPreference) - ConvertUtils.dp2px(10f)
}

这是我在 Kotlin 中编写的 扩展函数RecyclerView 一起使用(基于@Paul Woitaschek 的回答):

fun RecyclerView.smoothSnapToPosition(position: Int, snapMode: Int = LinearSmoothScroller.SNAP_TO_START) {
  val smoothScroller = object : LinearSmoothScroller(this.context) {
    override fun getVerticalSnapPreference(): Int = snapMode
    override fun getHorizontalSnapPreference(): Int = snapMode
  }
  smoothScroller.targetPosition = position
  layoutManager?.startSmoothScroll(smoothScroller)
}

这样使用:

myRecyclerView.smoothSnapToPosition(itemPosition)

我是这样使用的:

recyclerView.getLayoutManager().smoothScrollToPosition(recyclerView, new RecyclerView.State(), 5);

谢谢@droidev 的解决方案。如果有人在寻找 Kotlin 解决方案,请参考:

    class LinearLayoutManagerWithSmoothScroller: LinearLayoutManager {
    constructor(context: Context) : this(context, VERTICAL,false)
    constructor(context: Context, orientation: Int, reverseValue: Boolean) : super(context, orientation, reverseValue)

    override fun smoothScrollToPosition(recyclerView: RecyclerView?, state: RecyclerView.State?, position: Int) {
        super.smoothScrollToPosition(recyclerView, state, position)
        val smoothScroller = TopSnappedSmoothScroller(recyclerView?.context)
        smoothScroller.targetPosition = position
        startSmoothScroll(smoothScroller)
    }

    private class TopSnappedSmoothScroller(context: Context?) : LinearSmoothScroller(context){
        var mContext = context
        override fun computeScrollVectorForPosition(targetPosition: Int): PointF? {
            return LinearLayoutManagerWithSmoothScroller(mContext as Context)
                    .computeScrollVectorForPosition(targetPosition)
        }

        override fun getVerticalSnapPreference(): Int {
            return SNAP_TO_START
        }


    }

}

我想更全面地解决 滚动持续时间 的问题,如果您选择任何较早的答案,该问题实际上会根据数量的不同而有很大差异(并且令人无法接受)从当前位置到达目标位置所需的滚动次数。

要获得统一的滚动持续时间,速度(像素/毫秒)必须考虑到每个单独项目的大小 - 如果项目是非标准尺寸,则会增加一个全新的复杂程度。

这可能就是 RecyclerView 开发人员部署 too-hard 篮子以实现平滑滚动这一重要方面的原因。

假设您想要 半均匀 滚动持续时间,并且您的列表包含 半均匀 项,那么您将需要一些东西像这样。

/** Smoothly scroll to specified position allowing for interval specification. <br>
 * Note crude deceleration towards end of scroll
 * @param rv        Your RecyclerView
 * @param toPos     Position to scroll to
 * @param duration  Approximate desired duration of scroll (ms)
 * @throws IllegalArgumentException */
private static void smoothScroll(RecyclerView rv, int toPos, int duration) throws IllegalArgumentException {
    int TARGET_SEEK_SCROLL_DISTANCE_PX = 10000;     // See androidx.recyclerview.widget.LinearSmoothScroller
    int itemHeight = rv.getChildAt(0).getHeight();  // Height of first visible view! NB: ViewGroup method!
    itemHeight = itemHeight + 33;                   // Example pixel Adjustment for decoration?
    int fvPos = ((LinearLayoutManager)rv.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
    int i = Math.abs((fvPos - toPos) * itemHeight);
    if (i == 0) { i = (int) Math.abs(rv.getChildAt(0).getY()); }
    final int totalPix = i;                         // Best guess: Total number of pixels to scroll
    RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(rv.getContext()) {
        @Override protected int getVerticalSnapPreference() {
            return LinearSmoothScroller.SNAP_TO_START;
        }
        @Override protected int calculateTimeForScrolling(int dx) {
            int ms = (int) ( duration * dx / (float)totalPix );
            // Now double the interval for the last fling.
            if (dx < TARGET_SEEK_SCROLL_DISTANCE_PX ) { ms = ms*2; } // Crude deceleration!
            //lg(format("For dx=%d we allot %dms", dx, ms));
            return ms;
        }
    };
    //lg(format("Total pixels from = %d to %d = %d [ itemHeight=%dpix ]", fvPos, toPos, totalPix, itemHeight));
    smoothScroller.setTargetPosition(toPos);
    rv.getLayoutManager().startSmoothScroll(smoothScroller);
}

PS: 我诅咒我开始的那一天 不分青红皂白地 转换 ListViewRecyclerView.

  1. 扩展 "LinearLayout" class 并覆盖必要的功能
  2. 在您的片段中创建上述 class 的实例或 activity
  3. 调用“recyclerView.smoothScrollToPosition(targetPosition)

CustomLinearLayout.kt :

class CustomLayoutManager(private val context: Context, layoutDirection: Int):
  LinearLayoutManager(context, layoutDirection, false) {

    companion object {
      // This determines how smooth the scrolling will be
      private
      const val MILLISECONDS_PER_INCH = 300f
    }

    override fun smoothScrollToPosition(recyclerView: RecyclerView, state: RecyclerView.State, position: Int) {

      val smoothScroller: LinearSmoothScroller = object: LinearSmoothScroller(context) {

        fun dp2px(dpValue: Float): Int {
          val scale = context.resources.displayMetrics.density
          return (dpValue * scale + 0.5f).toInt()
        }

        // change this and the return super type to "calculateDyToMakeVisible" if the layout direction is set to VERTICAL
        override fun calculateDxToMakeVisible(view: View ? , snapPreference : Int): Int {
          return super.calculateDxToMakeVisible(view, SNAP_TO_END) - dp2px(50f)
        }

        //This controls the direction in which smoothScroll looks for your view
        override fun computeScrollVectorForPosition(targetPosition: Int): PointF ? {
          return this @CustomLayoutManager.computeScrollVectorForPosition(targetPosition)
        }

        //This returns the milliseconds it takes to scroll one pixel.
        override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float {
          return MILLISECONDS_PER_INCH / displayMetrics.densityDpi
        }
      }
      smoothScroller.targetPosition = position
      startSmoothScroll(smoothScroller)
    }
  }

注意:上面的例子设置为HORIZONTAL方向,可以在初始化的时候传VERTICAL/HORIZONTAL。

如果将方向设置为 VERTICAL,则应将“calculateDxToMakeVisible”更改为“calculateDyToMakeVisible”(还要注意超类型调用 return 值)

Activity/Fragment.kt :

...
smoothScrollerLayoutManager = CustomLayoutManager(context, LinearLayoutManager.HORIZONTAL)
recyclerView.layoutManager = smoothScrollerLayoutManager
.
.
.
fun onClick() {
  // targetPosition passed from the adapter to activity/fragment
  recyclerView.smoothScrollToPosition(targetPosition)
}

您可以通过 list.reverse() 反转列表,最后调用 RecylerView.scrollToPosition(0)

    list.reverse()
    layout = LinearLayoutManager(this,LinearLayoutManager.VERTICAL,true)  
    RecylerView.scrollToPosition(0)

我创建了一个基于项目在列表中的位置的扩展方法,它与回收站视图绑定

大列表中的平滑滚动需要更长的滚动时间,使用它来提高滚动速度并且还有平滑的滚动动画。干杯!

fun RecyclerView?.perfectScroll(size: Int,up:Boolean = true ,smooth: Boolean = true) {
this?.apply {
    if (size > 0) {
        if (smooth) {
            val minDirectScroll = 10 // left item to scroll
            //smooth scroll
            if (size > minDirectScroll) {
                //scroll directly to certain position
                val newSize = if (up) minDirectScroll else size - minDirectScroll
                //scroll to new position
                val newPos = newSize  - 1
                //direct scroll
                scrollToPosition(newPos)
                //smooth scroll to rest
                perfectScroll(minDirectScroll, true)

            } else {
                //direct smooth scroll
                smoothScrollToPosition(if (up) 0 else size-1)
            }
        } else {
            //direct scroll
            scrollToPosition(if (up) 0 else size-1)
        }
    }
} }

只需使用

在任何地方调用该方法
rvList.perfectScroll(list.size,up=true,smooth=true)