Skip to content

Instantly share code, notes, and snippets.

@lukelorusso
Last active June 14, 2021 16:54
Show Gist options
  • Save lukelorusso/98831eb27ca4e94c40b444991b1a33d8 to your computer and use it in GitHub Desktop.
Save lukelorusso/98831eb27ca4e94c40b444991b1a33d8 to your computer and use it in GitHub Desktop.
Now it's complete
fun RecyclerView.bindScrollTo(vararg destinations: RecyclerView): RecyclerView.OnScrollListener {
object : RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
// each time you drag a RecyclerView, you should STOP other destinations' scrolling
if (newState == RecyclerView.SCROLL_STATE_DRAGGING)
destinations.forEach { destinationRecyclerView ->
destinationRecyclerView.stopScroll()
}
// then you can scroll the RecyclerView, dragged or not
super.onScrollStateChanged(recyclerView, newState)
}
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
// when you scroll a RecyclerView of some [dx, dy] you can do it
super.onScrolled(recyclerView, dx, dy)
// and then, ONLY if this RecyclerView is NOT idle, you can propagate that scroll
// (this is to avoid infinite multiplications of [dx, dy] when calling scrollBy)
if (recyclerView.scrollState != RecyclerView.SCROLL_STATE_IDLE)
destinations.forEach { destinationRecyclerView ->
destinationRecyclerView.scrollBy(dx, dy)
}
}
}.also { listener ->
this.addOnScrollListener(listener)
return listener
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment