How to use RecyclerView.scrollToPosition() to move the position to the top of current view?

The RecyclerView.scrollToPosition() is extremely strange. for example, supposed a RecyclerView named "rv".

  1. if now item 10 is under the current RecyclerView, call rv.scrollToPosition(10), the RecyclerView will scroll item 10 to bottom.

  2. if now item 10 is in the current RecyclerView, call rv.scrollToPosition(10), there won't be any scrolling, nothing will be done.

  3. if now item 10 is on the top of the current RecyclerView, call rv.scrollToPosition(10), the RecyclerView will scroll item 10 to top.

To help understanding, look at this picture enter image description here

But what i need is that, whenever i call it, the RecyclerView will scroll the supposed position to the top of current view just like case 3. How to do that?


If I understand the question, you want to scroll to a specific position but that position is the adapter's position and not the RecyclerView's item position.

You can only achieve this through the LayoutManager.

Do something like:

rv.getLayoutManager().scrollToPosition(youPositionInTheAdapter).

Below link might solve your problem:

https://stackoverflow.com/a/43505830/4849554

Just create a SmoothScroller with the preference SNAP_TO_START:

RecyclerView.SmoothScroller smoothScroller = new 
LinearSmoothScroller(context) {
   @Override protected int getVerticalSnapPreference() {
       return LinearSmoothScroller.SNAP_TO_START;
   }
};

Now you set the position where you want to scroll to:

smoothScroller.setTargetPosition(position);

And pass that SmoothScroller to the LayoutManager:

layoutManager.startSmoothScroll(smoothScroller);