Distwo Distwo - 11 months ago 144
Android Question

Scroll RecyclerView to show selected item on top

I'm looking for a way to scroll a

to show the selected item on top.

In a
I was able to do that by using
and getting the top of the element that need to be centered.

Something like:

public void onItemClick(View v, int pos){
mylistView.scrollTo(0, v.getTop());

The problem is that the
returns an error when using it's
method saying

RecyclerView does not support scrolling to an absolute position

How can I scroll a
to put the selected item at the top of the view?

Answer Source

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:

//Scroll item 2 to 20 pixels from the top
linearLayoutManager.scrollToPositionWithOffset(2, 20);