1.調(diào)用滾動(dòng)代碼
recycler.smoothScrollToPosition(position)
2.設(shè)置滾動(dòng)代碼
recycler.layoutManager = ScrollSpeedLinearLayoutManger(mContext)
3.控制滾動(dòng)速度源代碼
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
}
}
}
關(guān)鍵在于 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使子視圖的左側(cè)或頂部與父視圖的左側(cè)或頂部對(duì)齊
SNAP_TO_END使子視圖的右側(cè)或底部與父視圖的右側(cè)面或底部對(duì)齊
SNAP_TO_ANY根據(jù)子視圖的當(dāng)前位置與父布局的關(guān)系,決定子視圖是否從頭到尾跟隨
比如,如果子視圖實(shí)際位于RecyclerView的左側(cè),SNAP_TO_ANY和SNAP_TO_START是沒(méi)有差別的
默認(rèn)值是SNAP_TO_ANY