4

I wish to understand why I can't seem to use the scrollToPositionWithOffset method on a LinearLayoutManager? Please see the image for what I mean :

scrollToPositionWithOffset not found!

A little background:

The first line in the image (with scrollToPosition) is scrolling the RecyclerView to make the position (in this case 50) visible - this often means that the selected position shows up at the bottom of the visible RecyclerView (where position 50 first becomes visible after 'scrolling'). Whereas I want to always show it at the top. From my research, a some-what solution seems to be to use this scrollToPositionWithOffset method (Scroll RecyclerView to show selected item on top)

Interestingly, I was able to achieve what I wanted by customizing SmoothScroller of LinearLayoutManager, but my dataset is huge so speed of 'smooth scrolling' is an issue, and I can't seem increase the speed enough without causing other issues.

In short, I'm hoping that scrollToPositionWithOffset will do the trick for me. However, I don't know how to access the method.

halfer
  • 19,824
  • 17
  • 99
  • 186
John Paoletto
  • 141
  • 2
  • 13

3 Answers3

6

You need to cast the LayoutManager returned from RecyclerView.getLayoutManager().

(recyclerview.layoutManager as LinearLayoutManager).scrollToPositionWithOffset

veritas1
  • 8,740
  • 6
  • 27
  • 37
1

Here is how:

recyclerView.apply { 
      
    (layoutManager as LinearLayoutManager).scrollToPositionWithOffset(itemPosition, offsetValue)

}

Note that offsetValue could be X if your list/recycleView has horizontal orientation or Y if your list/recycleView has vertical orientation.

Osama Remlawi
  • 2,356
  • 20
  • 21
0

To provide a little more context to the other answers, scrollToPositionWithOffset() is not a method of LayoutManager (the base class), but one of LinearLayoutManager (and its subclasses). My assumption is that the reasoning here was that such a method is not necessarily applicable (or could be ambiguous) for other LayoutManagers. Suppose we have a more "exotic" layout manager which does not organize items as a simple list, but rather in a circular shape. What should the offset do in such a case? Does it represent an extra amount radians/degrees to add to the scroll? Or rather something else?

In the case of a LinearLayoutManager (and any derived classes), however, it is fairly clear what the offset should do. Please correct me if I'm wrong, but I think that's why only LinearLayoutManagers have access to the method, hence requiring a cast of the RecyclerView's LayoutManager.

Tom D.
  • 1
  • 1