2019-06-27 RecyclerView滚动到指定位置置顶

2019-06-27  本文已影响0人  兣甅

1.调用滚动代码

recycler.smoothScrollToPosition(position)

2.设置滚动代码

recycler.layoutManager = ScrollSpeedLinearLayoutManger(mContext)

3.控制滚动速度源代码

package com.aimymusic.android.comm.ui.view.layoutmanager

import android.content.Context
import android.graphics.PointF
import android.support.annotation.Nullable
import android.support.v7.widget.*
import android.util.DisplayMetrics
class ScrollSpeedLinearLayoutManger(context: Context) :
  LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false) {

  var speed = 0.2f

  override fun smoothScrollToPosition(
    recyclerView: RecyclerView,
    state: RecyclerView.State?,
    position: Int
  ) {
    val smoothScroller = TopSmoothScroller(recyclerView.context)
    smoothScroller.targetPosition = position
    startSmoothScroll(smoothScroller)
  }

  private inner class TopSmoothScroller internal constructor(context: Context) :
    LinearSmoothScroller(context) {

    @Nullable
    override fun computeScrollVectorForPosition(targetPosition: Int): PointF? {
      return this@ScrollSpeedLinearLayoutManger.computeScrollVectorForPosition(targetPosition)
    }

    override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics): Float {
      return speed
    }

    override fun getVerticalSnapPreference(): Int {
      return LinearSmoothScroller.SNAP_TO_START
    }

    override fun getHorizontalSnapPreference(): Int {
      return LinearSmoothScroller.SNAP_TO_START
    }
  }
}

关键在于 getVerticalSnapPreference()的返回值,共有三种

public static final int SNAP_TO_START = -1; 
 public static final int SNAP_TO_END = 1;
 public static final int SNAP_TO_ANY = 0;

SNAP_TO_START使子视图的左侧或顶部与父视图的左侧或顶部对齐
SNAP_TO_END使子视图的右侧或底部与父视图的右侧面或底部对齐
SNAP_TO_ANY根据子视图的当前位置与父布局的关系,决定子视图是否从头到尾跟随
比如,如果子视图实际位于RecyclerView的左侧,SNAP_TO_ANY和SNAP_TO_START是没有差别的
默认值是SNAP_TO_ANY

上一篇下一篇

猜你喜欢

热点阅读