1. 实现平滑滚动
自定义 CenterSmoothScroller 实现LinearSmoothScroller
class CenterSmoothScroller(context: Context) : LinearSmoothScroller(context) { override fun calculateDtToFit( viewStart: Int, viewEnd: Int, boxStart: Int, boxEnd: Int, snapPreference: Int ): Int { return (boxStart + boxEnd) / 2 - (viewStart + viewEnd) / 2 } }
2. 自定义smoothScrollToPositionView的函数
private fun smoothScrollToPositionView(recyclerView: RecyclerView, position: Int) { val context = recyclerView.context val layoutManager = recyclerView.layoutManager as LinearLayoutManager val smoothScroller = CenterSmoothScroller(context) smoothScroller.targetPosition = position // 开始平滑滚动 layoutManager.startSmoothScroll(smoothScroller) }
3. 自己的页面调用方法:实现scrollToPosition 方法;用 recyclerView.post
private fun scrollToPosition() { val position = 10 //假设是10,开发者根据自己的逻辑更改 //此处用recyclerView.post 的方法,目的是 recyclerView 整体管理布局ok后,再实现滚动; recyclerView.post { smoothScrollToPositionView(recyclerView, position) } }