Reputation: 677
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?
Upvotes: 2
Views: 771
Reputation: 40830
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));
Upvotes: 5