Skip to content

Instantly share code, notes, and snippets.

@dadouf
Created December 11, 2020 10:42
Show Gist options
  • Save dadouf/a2bfab7c59cdfc272047598c750235ff to your computer and use it in GitHub Desktop.
Save dadouf/a2bfab7c59cdfc272047598c750235ff to your computer and use it in GitHub Desktop.
vh.imageView.setOnClickListener {
val rv = vh.imageView.parent as RecyclerView
rv.smoothScrollToCenteredPosition(position)
}
fun RecyclerView.smoothScrollToCenteredPosition(position: Int) {
val smoothScroller = object : LinearSmoothScroller(context) {
override fun calculateDxToMakeVisible(view: View?,
snapPref: Int): Int {
val dxToStart = super.calculateDxToMakeVisible(view, SNAP_TO_START)
val dxToEnd = super.calculateDxToMakeVisible(view, SNAP_TO_END)
return (dxToStart + dxToEnd) / 2
}
}
smoothScroller.targetPosition = position
layoutManager?.startSmoothScroll(smoothScroller)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment