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

问题描述 投票:0回答:6

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一样。如何做到这一点?

android scroll android-recyclerview
6个回答
66
投票

如果我理解这个问题,您想滚动到特定位置,但该位置是适配器的位置,而不是

RecyclerView
的项目位置。

您只能通过

LayoutManager
来实现这一点。

做类似的事情:

rv.getLayoutManager().scrollToPosition(youPositionInTheAdapter).

28
投票

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

https://stackoverflow.com/a/43505830/4849554

只需使用首选项 SNAP_TO_START 创建一个 SmoothScroller:

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

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

smoothScroller.setTargetPosition(position);

并将 SmoothScroller 传递给 LayoutManager:

layoutManager.startSmoothScroll(smoothScroller);

6
投票

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

lateinit var layoutManager: LinearLayoutManager

fun setupView() {
    ...

    layoutManager = LinearLayoutManager(applicationContext)
    mainRecyclerView.layoutManager = layoutManager

    ...
}

fun moveToPosition(position: Int) {
    layoutManager.scrollToPositionWithOffset(position, 0)
}

5
投票

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

StaggeredGridLayoutManager
scrollToPosition

   StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
   staggeredGridLayoutManager.scrollToPosition(10);
   recyclerView.setLayoutManager(staggeredGridLayoutManager);

0
投票

尝试

recycler_view.smoothScrollBy(0, 100);
这里0代表
x-coordinate
100代表
y-coordinate
我在垂直recyclerView中使用了它,我想滚动到垂直列表中的下一个位置,为了到达上一个位置我简单地替换了 100-100


0
投票

这个 API 适合您。

int 偏移量=0; recyclerView.scrollToPositionWithOffset(位置,偏移量);

© www.soinside.com 2019 - 2024. All rights reserved.