自动滚动的RecyclerView

265 阅读1分钟

每3秒自动滚动2个位置的横向recyclerview 适配器itemCount设置为Int.MAX_VALUE

class CustomScrollRecyclerView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyle: Int = 0) :  
RecyclerView(context, attrs, defStyle) {  
init {  
layoutManager = LinearLayoutManager(context).apply { orientation = HORIZONTAL }  
addOnScrollListener(object : OnScrollListener() {  
override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {  
if (newState == SCROLL_STATE_IDLE) {  
startScroll()  
} else {  
removeCallbacks(marqueeRunnable)  
}  
}  
})  
}  
  
private val smoothScroller by lazy {  
object : LinearSmoothScroller(context) {  
override fun getHorizontalSnapPreference(): Int {  
return SNAP_TO_START  
}  
  
override fun getVerticalSnapPreference(): Int {  
return SNAP_TO_START  
}  
  
override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics?): Float {  
if (displayMetrics != null) {  
return 300f / displayMetrics.densityDpi  
}  
return super.calculateSpeedPerPixel(null)  
}  
}  
}  
  
private fun smoothNextPosition(rv: RecyclerView) {  
runCatching {  
val llm = rv.layoutManager as LinearLayoutManager  
val nextPosition: Int = llm.findFirstVisibleItemPosition() + 2  
smoothScroller.targetPosition = nextPosition  
llm.startSmoothScroll(smoothScroller)  
}  
}  
  
private val marqueeRunnable = Runnable { smoothNextPosition(this) }  
  
fun startScroll() {  
removeCallbacks(marqueeRunnable)  
postDelayed(marqueeRunnable, 3000)  
}  
  
override fun onDetachedFromWindow() {  
super.onDetachedFromWindow()  
removeCallbacks(marqueeRunnable)  
scrollToPosition(0)  
}  
  
override fun onAttachedToWindow() {  
super.onAttachedToWindow()  
startScroll()  
}  
  
}