RecyclerView.scrollToPosition()
非常奇怪。
例如,假设 RecyclerView
名为 "rv"
。
如果现在第 10 项位于当前
RecyclerView
下方,则调用 rv.scrollToPosition(10)
,RecyclerView
会将第 10 项滚动到底部。如果现在第10项在当前
RecyclerView
中,则调用rv.scrollToPosition(10)
,不会有任何滚动,什么也不做。如果现在第 10 项位于当前
RecyclerView
的顶部,则调用 rv.scrollToPosition(10)
,RecyclerView
会将第 10 项滚动到顶部。但是我需要的是,每当我调用它时,
RecyclerView
都会将假定的位置滚动到当前视图的顶部,就像情况3一样。如何做到这一点?
如果我理解这个问题,您想滚动到特定位置,但该位置是适配器的位置,而不是
RecyclerView
的项目位置。
您只能通过
LayoutManager
来实现这一点。
做类似的事情:
rv.getLayoutManager().scrollToPosition(youPositionInTheAdapter).
下面的链接可能会解决您的问题:
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);
这是 Kotlin 代码片段,但您可以正确地按位置滚动到项目。重点是声明布局管理器的成员变量并使用其方法来滚动。
lateinit var layoutManager: LinearLayoutManager
fun setupView() {
...
layoutManager = LinearLayoutManager(applicationContext)
mainRecyclerView.layoutManager = layoutManager
...
}
fun moveToPosition(position: Int) {
layoutManager.scrollToPositionWithOffset(position, 0)
}
如果您想滚动到特定位置并且该位置是适配器的位置,那么您可以使用
StaggeredGridLayoutManager
scrollToPosition
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(1, StaggeredGridLayoutManager.VERTICAL);
staggeredGridLayoutManager.scrollToPosition(10);
recyclerView.setLayoutManager(staggeredGridLayoutManager);
尝试
recycler_view.smoothScrollBy(0, 100);
这里0代表x-coordinate
和100代表y-coordinate
我在垂直recyclerView中使用了它,我想滚动到垂直列表中的下一个位置,为了到达上一个位置我简单地替换了 100 与 -100
这个 API 适合您。
int 偏移量=0; recyclerView.scrollToPositionWithOffset(位置,偏移量);