首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >RecyclerView -如何平滑滚动到某一位置上的项目顶部?

RecyclerView -如何平滑滚动到某一位置上的项目顶部?
EN

Stack Overflow用户
提问于 2015-07-05 21:30:17
回答 14查看 150.9K关注 0票数 167

在RecyclerView上,我可以通过以下方法突然滚动到所选项目的顶部:

代码语言:javascript
运行
复制
((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(position, 0);

但是,这会突然将项目移到最高位置。我想移动到一个项目的顶部平滑的

我也试过:

代码语言:javascript
运行
复制
recyclerView.smoothScrollToPosition(position);

但是,它不能很好地工作,因为它没有将项目移动到选定的位置到顶部。它只是滚动列表,直到位置上的项目可见为止。

EN

Stack Overflow用户

发布于 2019-12-11 11:38:24

  1. 扩展"LinearLayout“类并覆盖必要的函数
  2. 在片段或活动中创建上述类的实例。
  3. 调用"recyclerView.smoothScrollToPosition(targetPosition)

CustomLinearLayout.kt :

代码语言:javascript
运行
复制
class CustomLayoutManager(private val context: Context, layoutDirection: Int):
  LinearLayoutManager(context, layoutDirection, false) {

    companion object {
      // This determines how smooth the scrolling will be
      private
      const val MILLISECONDS_PER_INCH = 300f
    }

    override fun smoothScrollToPosition(recyclerView: RecyclerView, state: RecyclerView.State, position: Int) {

      val smoothScroller: LinearSmoothScroller = object: LinearSmoothScroller(context) {

        fun dp2px(dpValue: Float): Int {
          val scale = context.resources.displayMetrics.density
          return (dpValue * scale + 0.5f).toInt()
        }

        // change this and the return super type to "calculateDyToMakeVisible" if the layout direction is set to VERTICAL
        override fun calculateDxToMakeVisible(view: View ? , snapPreference : Int): Int {
          return super.calculateDxToMakeVisible(view, SNAP_TO_END) - dp2px(50f)
        }

        //This controls the direction in which smoothScroll looks for your view
        override fun computeScrollVectorForPosition(targetPosition: Int): PointF ? {
          return this @CustomLayoutManager.computeScrollVectorForPosition(targetPosition)
        }

        //This returns the milliseconds it takes to scroll one pixel.
        override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float {
          return MILLISECONDS_PER_INCH / displayMetrics.densityDpi
        }
      }
      smoothScroller.targetPosition = position
      startSmoothScroll(smoothScroller)
    }
  }

注意:上面的示例设置为水平方向,您可以在初始化期间传递垂直/水平。

如果将方向设置为"calculateDxToMakeVisible“垂直,则应将更改为"calculateDyToMakeVisible”(还要注意超级类型的调用返回值)

Activity/Fragment.kt:

代码语言:javascript
运行
复制
...
smoothScrollerLayoutManager = CustomLayoutManager(context, LinearLayoutManager.HORIZONTAL)
recyclerView.layoutManager = smoothScrollerLayoutManager
.
.
.
fun onClick() {
  // targetPosition passed from the adapter to activity/fragment
  recyclerView.smoothScrollToPosition(targetPosition)
}
票数 1
EN
查看全部 14 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31235183

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档