class CenterLayoutManager(context: Context?) : LinearLayoutManager(context) {
override fun smoothScrollToPosition(recyclerView: RecyclerView, state: RecyclerView.State?, position: Int) {
val smoothScroller: RecyclerView.SmoothScroller = CenterSmoothScroller(recyclerView.context)
smoothScroller.targetPosition = position
startSmoothScroll(smoothScroller)
}
private class CenterSmoothScroller(context: Context?) : LinearSmoothScroller(context) {
override fun calculateDtToFit(viewStart: Int, viewEnd: Int, boxStart: Int, boxEnd: Int, snapPreference: Int): Int {
return (boxStart + (boxEnd - boxStart) / 2) - (viewStart + (viewEnd - viewStart) / 2)
}
override fun calculateTimeForScrolling(dx: Int): Int {
return 100
}
}
}
调用
val manager = CenterLayoutManager(context)
manager.orientation = RecyclerView.HORIZONTAL
mRecyclerView.layoutManager = manager
(mRecyclerView.layoutManager as CenterLayoutManager)
.smoothScrollToPosition(mRecyclerView, RecyclerView.State(), mCurrentPosition)