My vertical RecyclerView (looking like a simple list) in Kotlin scrolls neatly to the next element when I press a button. However when the next element is off screen (for example because in the meantime the user scrolled to a different position with a gesture) the problem is that this doesn't work anymore. Instead, it automatically scrolls all the way to the bottom of the RecyclerView.
Any idea how to fix that? I'd appreciate it! Thanks in advance for your efforts.
I'm overriding SmoothScrollLinearLayoutManager:
class SmoothScrollLinearLayoutManager(private val mContext: Context, orientation: Int, reverseLayout: Boolean) : LinearLayoutManager(mContext, orientation, reverseLayout) {
override fun smoothScrollToPosition(recyclerView: RecyclerView, state: RecyclerView.State?,
position: Int) {
val smoothScroller = object : TopSnappedSmoothScroller(recyclerView.context) {
//This controls the direction in which smoothScroll looks for your view
override fun computeScrollVectorForPosition(targetPosition: Int): PointF {
return PointF(0f, 1f)
}
//This returns the milliseconds it takes to scroll one pixel.
protected override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float {
return MILLISECONDS_PER_INCH / displayMetrics.densityDpi
}
}
smoothScroller.targetPosition = position
Log.i("Target", smoothScroller.targetPosition.toString())
startSmoothScroll(smoothScroller)
}
private open inner class TopSnappedSmoothScroller(context: Context) : LinearSmoothScroller(context) {
override fun computeScrollVectorForPosition(targetPosition: Int): PointF? {
return this@SmoothScrollLinearLayoutManager
.computeScrollVectorForPosition(targetPosition)
}
override fun getVerticalSnapPreference(): Int {
return LinearSmoothScroller.SNAP_TO_START
}
}
private open inner class CenterSnappedSmoothScroller(context: Context) : LinearSmoothScroller(context) {
override fun computeScrollVectorForPosition(targetPosition: Int): PointF? {
return this@SmoothScrollLinearLayoutManager
.computeScrollVectorForPosition(targetPosition)
}
override fun getVerticalSnapPreference(): Int {
return LinearSmoothScroller.SNAP_TO_END
}
}
// Scrolling speed
companion object {
private val MILLISECONDS_PER_INCH = 110f
}
}
The button triggers this function to scroll to the next element in the list (RecyclerView):
private fun fastForwardTapped() {
// Update selected position in RecyclerView
selectedPosition += 1
recyclerView.smoothScrollToPosition(selectedPosition)
}