Scroll RecyclerView Scroll to position always on top

erluxman picture erluxman · Aug 7, 2016 · Viewed 14.9k times · Source

I'm using linear layout manager and RecyclerView with a LinearLayout Manager to populate some list of items. When I'm displaying the recyclerview for the first time and I use:

linearLayoutManager.scrollToPosition(desiredindex);

it scrolls to the top exactly where I want.

Now here is the tricky part - When I'm scrolling to top of recyclerview (i.e. new items indices will be lower than the desiredindex) and I call:

linearLayoutManager.scrollToPosition(desiredindex);

It still works fine, but when the recyclerview has been scrolled beyond the desiredindex, the recycler view scrolls such that the desiredindex item comes to the bottom rather than on top, but I want the tile to scroll to the top not the bottom.

Answer

nshmura picture nshmura · Aug 7, 2016

Use scrollToPositionWithOffset like this:

linearLayoutManager.scrollToPositionWithOffset(desiredindex, 0);

scrolltopositionwithoffset(position, offset) forces the indicated item visible with indicated offset. The offset is distance from the top of RecyclerView.