You need to enable JavaScript to run this app. RecyclerView 如何设置自定义滚动插值器(含代码创建实现示例)
优惠活动
大模型
产品
解决方案
定价
更多

RecyclerView 如何设置自定义滚动插值器(含代码创建实现示例)

为编程方式创建的RecyclerView设置自定义滚动插值器

RecyclerView的滚动插值器和LayoutManager的平滑滚动逻辑绑定,无法直接通过RecyclerView实例设置,你可以通过自定义LinearSmoothScroller注入自定义插值器,修改后的代码如下:

import android.util.DisplayMetrics
import android.view.animation.DecelerateInterpolator
import android.view.animation.Interpolator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.LinearSmoothScroller
import androidx.recyclerview.widget.RecyclerView

private fun initRecyclerView() {
    // 初始化自定义滚动插值器,可替换为你自己实现的Interpolator实例
    val customInterpolator: Interpolator = DecelerateInterpolator(2f)
    
    RecyclerView(context).apply {
        setHasFixedSize(true)
        // 重写LinearLayoutManager的平滑滚动逻辑,绑定自定义Scroller
        layoutManager = object : LinearLayoutManager(context, VERTICAL, true) {
            override fun smoothScrollToPosition(recyclerView: RecyclerView, state: RecyclerView.State?, position: Int) {
                val customScroller = object : LinearSmoothScroller(recyclerView.context) {
                    override fun getInterpolator(): Interpolator = customInterpolator
                    
                    // 可选:重写该方法调整滚动速度,数值越小滚动速度越快
                    override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float {
                        return 0.25f / displayMetrics.densityDpi
                    }
                }
                customScroller.targetPosition = position
                startSmoothScroll(customScroller)
            }
        }
        adapter = SlotAdapter().apply { submitList(cells) }
    }
    addView(slot)
}
  • 你可以将上述代码中的customInterpolator替换为任意系统内置插值器(如OvershootInterpolator、AccelerateInterpolator),或是你自定义实现的Interpolator子类实例,修改后所有触发smoothScrollToPosition的滚动行为都会使用你设置的插值器
  • 如果不需要全局修改插值器,仅需要单次滚动使用自定义插值器,可直接在触发滚动的位置单独创建自定义LinearSmoothScroller执行即可,不需要重写LayoutManager

内容的提问来源于stack exchange,提问作者Владислав Шестернин

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.10 16:24:00