英文:
RecyclerView scrollToPosition() puts the item on BOTTOM. How do I get it to TOP?
问题
我有一个显示垂直字符串列表的 RecyclerView
:
行0
行1
行2
行3
行4
...
我正在使用函数 recyclerView.scrollToPosition(position);
跳转到某一行。然而,我想要跳转到的行实际上出现在视图的底部!
例如,如果我执行 recyclerView.scrollToPosition(17);
,结果如下:
行13
行14
行15
行16
行17 <--- 17 在底部(最后可见行)
我想要的是:
行17 <-- 17 在顶部(第一个可见行)
行18
行19
行20
行21
我该如何实现这一点?
英文:
I have a RecyclerView
that displays a vertical list of strings:
Row0
Row1
Row2
Row3
Row4
...
I'm using the function recyclerView.scrollToPosition(position);
to jump to a row. However, the row I want to jump to, ends up on the BOTTOM of the view!
For example if I do recyclerView.scrollToPosition(17);
I get:
Row13
Row14
Row15
Row16
Row17 <--- 17 is at bottom (last visible row)
What I want is:
Row17 <-- 17 to be on top (first visible row)
Row18
Row19
Row20
Row21
How can I achieve this?
答案1
得分: 5
.scrollToPosition()
的默认行为是一旦滚动到您要滚动到的行时停止滚动。您可以使用带有固定偏移量的scrollToPositionWithOffset()
,以便它与滚动值相加。
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
if (layoutManager != null) {
layoutManager.scrollToPositionWithOffset(position, 20);
}
更新
> 我该如何计算偏移量?我RecyclerView中的每一行高度都不同。而且我不知道如何测量它。
现在您可以计算屏幕上第一个和最后一个可见项目之间的差异,这仅在屏幕上最后一个可见项目是您要推到第一个的项目时才起作用。
layoutManager.scrollToPosition(position));
int firstItemPosition = ((LinearLayoutManager) recyclerview.getLayoutManager())
.findFirstCompletelyVisibleItemPosition();
int lastItemPosition = ((LinearLayoutManager) recyclerview.getLayoutManager())
.findLastCompletelyVisibleItemPosition();
layoutManager.scrollToPositionWithOffset(position,
Math.abs(lastItemPosition - firstItemPosition));
英文:
The default behavior of the .scrollToPosition()
is to stop scrolling once the row you scroll to shows up on the screen. You can use scrollToPositionWithOffset()
with a fixed offset, so that it sums up to the scroll value.
LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
if (layoutManager != null) {
layoutManager.scrollToPositionWithOffset(position, 20);
}
UPDATE
> how can I compute the offset value? Each row in my RecyclerView has a different height. Also I don't see how to measure it.
Now you can compute the difference between the first and last visible items on the screen and that will work only when the last visible item on the screen is current your item that you want to push to first.
layoutManager.scrollToPosition(position));
int firstItemPosition = ((LinearLayoutManager) recyclerview.getLayoutManager())
.findFirstCompletelyVisibleItemPosition();
int lastItemPosition = ((LinearLayoutManager) recyclerview.getLayoutManager())
.findLastCompletelyVisibleItemPosition();
layoutManager.scrollToPositionWithOffset(position,
Math.abs(lastItemPosition - firstItemPosition));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论