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


125

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

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

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

我也尝试过:

recyclerView.smoothScrollToPosition(position);

但是它不能很好地工作,因为它不能将项目移动到所选的顶部位置。它仅滚动列表,直到该位置上的项目可见为止。

Answers:


224

RecyclerView被设计为可扩展的,因此无需为了执行滚动而将其子类化LayoutManager(如droidev建议的那样)。

相反,只需创建一个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);

9
感谢您提供此较短的解决方案。在实现过程中,我还需要考虑两件事:当我具有水平滚动视图时,必须设置protected int getHorizontalSnapPreference() { return LinearSmoothScroller.SNAP_TO_START; }。此外,我必须实现抽象方法public PointF computeScrollVectorForPosition(int targetPosition) { return layoutManager.computeScrollVectorForPosition(targetPosition); }
AustrianDude

2
RecyclerView可能被设计为可扩展的,但是像这样的简单事情却很容易丢失。好的答案!谢谢。
迈克尔(Michael)

8
有什么办法让它快速启动,但偏移量为X dp?
Mark Buikema '18年

2
正是@Alessio,这将破坏RecyclerView的默认默认smoothScrollToPosition功能
droidev

4
有可能减慢速度吗?
Alireza Noorali

112

为此,您必须创建一个自定义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项的顶部。

希望这可以帮助。


我在执行建议的LayoutManager时遇到了麻烦。这个答案对我来说更容易工作:stackoverflow.com/questions/28025425/…–
arberg

3
经过数小时的痛苦后,这才是有用的答案,这是按设计的!
wblaschko

1
@droidev我将您的示例用于平滑滚动,通常需要SNAP_TO_START,但它对我来说有一些问题。有时,滚动会在我传递到的1,2,3或4个位置之前停止smoothScrollToPosition。为什么可能会出现此问题?谢谢。
娜塔莎

您能以某种方式向我们获取您的代码吗?我很确定这是您的代码问题。
droidev '16

1
尽管答案是正确的,但这仍然是正确的答案
Alessio '18

25

这是我在Kotlin中编写的扩展功能,可用于(基于@Paul Woitaschek的回答):RecyclerView

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)

这可行!平滑滚动的问题是,当您有较大的列表,然后滚动到底部或顶部需要很长时间时
Portfoliobuilder

@vovahost如何将所需位置居中?
ysfcyln


12

我们可以这样尝试

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

5

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

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

这就是我想要的。感谢您分享此实现以实现x / y的偏移位置:)
Shan Xeeshi19年

3

我发现滚动a的最简单方法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);

2
如果该位置已经可见,则不会滚动到该位置。它滚动显示位置所需的最少数量。因此,为什么我们需要一个具有指定偏移量的对象。
TatiOverflow

3

我曾经这样:

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

2

谢谢@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
        }


    }

}

1
感谢@pankaj,正在Kotlin寻找解决方案。
Akshay Kumar都

1
  1. 扩展“ LinearLayout”类并覆盖必要的功能
  2. 在片段或活动中创建上述类的实例
  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)
    }
  }

注意:上面的示例设置为“水平”方向,可以在初始化期间传递“垂直/水平”。

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

活动/Fragment.kt

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

0

@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元素的最高坐标;2.我们需要获取要滚动到顶部的视图项的顶部坐标;3.最后,我们需要计算偏移量

recyclerView.scrollBy(0, offset);

200仅是示例硬编码整数值,如果不存在viewholder项,则可以使用它,因为这也是可能的。


0

我想更全面地解决滚动持续时间的问题,如果您选择任何较早的答案,实际上会根据从当前位置到达目标位置所需的滚动量而发生巨大变化(并且是无法接受的)。

为了获得一致的滚动持续时间,速度(像素/毫秒)必须考虑每个单独项目的大小-并且当项目为非标准尺寸时,则会增加全新的复杂性。

这可能就是为什么RecyclerView开发人员将太过硬的篮子部署到平滑滚动这一至关重要的方面的原因。

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

/** 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:我诅咒有一天我开始不加选择地ListView转换为RecyclerView

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.