Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin/RecyclerView: scrollToPositionWithOffset Not Showing Up

Tags:

android

kotlin

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.

like image 499
John Paoletto Avatar asked Mar 05 '23 08:03

John Paoletto


2 Answers

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

(recyclerview.layoutManager as LinearLayoutManager).scrollToPositionWithOffset

like image 129
veritas1 Avatar answered Mar 10 '23 10:03

veritas1


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.

like image 31
Osama Remlawi Avatar answered Mar 10 '23 09:03

Osama Remlawi