In my RecyclerView
I have some items that user can scroll and see that. Now I want to save this position and scroll that after come back. This below code return
For a similar requirement plus some action needed to be performed on scroll state changed, I did this with a custom scroll listener:
class OnScrollListener(private val action: () -> Unit) : RecyclerView.OnScrollListener() {
private var actionExecuted: Boolean = false
private var oldScrollPosition: Int = 0
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
super.onScrollStateChanged(recyclerView, newState)
when (newState) {
RecyclerView.SCROLL_STATE_DRAGGING -> actionExecuted = false
RecyclerView.SCROLL_STATE_SETTLING -> actionExecuted = false
RecyclerView.SCROLL_STATE_IDLE -> {
val scrolledPosition =
(recyclerView.layoutManager as? LinearLayoutManager)?.findFirstVisibleItemPosition() ?: return
if (scrolledPosition != RecyclerView.NO_POSITION && scrolledPosition != oldScrollPosition && !actionExecuted) {
action.invoke()
actionExecuted = true
oldScrollPosition = scrolledPosition
}
}
}
}
}
This is because of the pre-existing bug with RecyclerView onScroll which happens to trigger the callback 2-3 or even more times. And if there is some action to be performed, that will end up executing multiple times.