RecyclerView滚动到某position并居中展示

128 阅读1分钟
class CenterLayoutManager(context: Context?) : LinearLayoutManager(context) {

    /**
     * 动态滚动到position
     */
    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) {

        /**
         * 滚动结束后对应position的ViewHolder在RecyclerView的正中间
         */
        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)