I'm looking for a way to scroll a RecyclerView
to show the selected item on top.
In a ListView
I was able to do that by using scrollTo(x,y)
and getting the top of the element that need to be centered.
Something like:
@Override
public void onItemClick(View v, int pos){
mylistView.scrollTo(0, v.getTop());
}
The problem is that the RecyclerView
returns an error when using it's scrollTo
method saying
RecyclerView does not support scrolling to an absolute position
How can I scroll a RecyclerView
to put the selected item at the top of the view?
just call this method simply:
instead of:
I use the code below to smooth-scroll an item (thisView) to the top.
It works also for GridLayoutManager with views of different heights:
Seems to work good enough for a quick solution.
If you are using the LinearLayoutManager or StaggeredGridLayoutManager, they each have a scrollToPositionWithOffset method that takes both the position and also the offset of the start of the item from the start of the RecyclerView, which seems like it would accomplish what you need (setting the offset to 0 should align with the top).
For instance:
what i did to restore the scroll position after refreshing the RecyclerView on button clicked:
getting the offset of the first visible item from the top before creating the linearLayoutManager object and after instantiating it the scrollToPositionWithOffset of the LinearLayoutManager object was called.
If you looking for vertical LinearLayout Manager you can achieve smooth scrolling using a custom
LinearSmoothScroller
:use an instance of the layoutmanager in recycle view and then calling
recyclerView.smoothScrollToPosition(pos);
will smooth scroll to selected position to top of the recycler view