RecyclerView - 如何在某个位置平滑滚动到项目顶部?

时间:2015-07-05 21:30:17

标签: android scroll position android-recyclerview smooth

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

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

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

我也尝试过:

recyclerView.smoothScrollToPosition(position);

但它不能正常工作,因为它不会将项目移动到选定位置的顶部。它只是滚动列表,直到位置上的项目可见。

13 个答案:

答案 0 :(得分:151)

RecyclerView旨在是可扩展的,因此不需要将LayoutManager(作为droidev suggested)子类化,只是为了执行滚动。

相反,只需使用首选项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);

答案 1 :(得分:102)

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

希望这会有所帮助。

答案 2 :(得分:5)

我们可以这样尝试

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

答案 3 :(得分:3)

我发现滚动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);

答案 4 :(得分:3)

这是我在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 {
            return snapMode
        }

        override fun getHorizontalSnapPreference(): Int {
            return snapMode
        }
    }
    smoothScroller.targetPosition = position
    layoutManager?.startSmoothScroll(smoothScroller)
}

像这样使用它:

myRecyclerView.smoothSnapToPosition(itemPosition)

答案 5 :(得分:1)

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


    }

}

答案 6 :(得分:1)

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

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

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)

答案 7 :(得分: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只是示例硬编码整数值,如果视图符号项不存在,您可以使用它,因为这也是可能的。

答案 8 :(得分:0)

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

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

答案 9 :(得分:0)

我这样使用:

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

答案 10 :(得分:0)

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

要获得统一的滚动持续时间,速度(像素/毫秒)必须考虑每个单独项目的大小-如果项目的尺寸不符合标准,则将复杂性提高到一个全新的水平。

这可能就是为什么 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:我诅咒我开始不加选择地 ListView 转换为 RecyclerView 的那一天。

答案 11 :(得分:0)

截至2019年末,考虑到AndroidX库中API的更改,唯一适用于已可见项目的解决方案如下:

  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 ”(还要注意超类型调用返回值)

Activity / Fragment.kt

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

答案 12 :(得分:-1)

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

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