如何使用RecyclerView.scrollToPosition()将位置移动到当前视图的顶部?

cry*_*yyy 26 android scroll android-recyclerview

RecyclerView.scrollToPosition()是非常奇怪的.例如,假设一个RecyclerView名字"rv".

  1. 如果现在项目10在当前RecyclerView,呼叫rv.scrollToPosition(10),RecyclerView则将项目10滚动到底部.

  2. 如果现在项目10在当前RecyclerView,呼叫rv.scrollToPosition(10),将不会有任何滚动,将不会做任何事情.

  3. 如果现在项目10位于当前的顶部,则RecyclerView调用rv.scrollToPosition(10),RecyclerView将项目10滚动到顶部.

为了帮助理解,请看这张照片 在此输入图像描述

但我需要的是,每当我调用它时,RecyclerView就会像案例3一样将所谓的位置滚动到当前视图的顶部.如何做到这一点?

yug*_*oid 45

如果我理解了这个问题,你想滚动到一个特定的位置,但该位置是适配器的位置,而不是RecyclerView项目的位置.

你只能通过这个来实现这一目标LayoutManager.

做类似的事情:

rv.getLayoutManager().scrollToPosition(youPositionInTheAdapter).
Run Code Online (Sandbox Code Playgroud)

  • 我确定这是不正确的.在RecyclerView上调用scrollToPosition只是在LayoutManager上调用相同的方法.它甚至在javadocs中说"RecyclerView没有实现滚动逻辑,而是将调用转发给android.support.v7.widget.RecyclerView.LayoutManager#scrollToPosition在RecyclerView或LayoutManager上调用scrollToPosition将具有完全相同的效果. (4认同)
  • 使用 LinearLayoutManager.scrollToPositionWithOffset(position, 0); (3认同)
  • @Castor 谢谢你。一个看似微小但关键的区别 - `scrollToPosition` 似乎确保目标视图在回收器中的某个位置(通常是底部)可见,而 `scrollToPositionWithOffset` `0` 确保目标视图在回收器的顶部可见。 (3认同)

Rit*_*esh 14

以下链接可能会解决您的问题:

/sf/answers/3045408131/

只需创建一个具有首选项SNAP_TO_START的SmoothScroller:

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

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

smoothScroller.setTargetPosition(position);
Run Code Online (Sandbox Code Playgroud)

并将SmoothScroller传递给LayoutManager:

layoutManager.startSmoothScroll(smoothScroller);
Run Code Online (Sandbox Code Playgroud)

  • 问题是我的RecyclerView有700个项目,所以如果到目标滚动的距离<30,那么我使用平滑滚动,这个代码完美无缺.但是如果到目标滚动的距离大于30,我想自动跳转到该项目.在那种情况下,我不想使用平滑滚动.如何"快速启动"该项目? (4认同)
  • 如果您想进行平滑滚动,那没问题,但是如果您想进行自动滚动呢? (3认同)
  • @AlexanderN.很好,我不知道那种方法.要尽快尝试. (2认同)

Cas*_*tor 6

这是 Kotlin 代码片段,但您可以正确地按位置滚动到项目。重点是声明布局管理器的成员变量并使用其方法进行滚动。

lateinit var layoutManager: LinearLayoutManager

fun setupView() {
    ...

    layoutManager = LinearLayoutManager(applicationContext)
    mainRecyclerView.layoutManager = layoutManager

    ...
}

fun moveToPosition(position: Int) {
    layoutManager.scrollToPositionWithOffset(position, 0)
}
Run Code Online (Sandbox Code Playgroud)


Zee*_*han 5

如果您想滚动到特定位置并且该位置是适配器的位置,那么您可以使用StaggeredGridLayoutManager scrollToPosition

   StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
   staggeredGridLayoutManager.scrollToPosition(10);
   recyclerView.setLayoutManager(staggeredGridLayoutManager);
Run Code Online (Sandbox Code Playgroud)