在开发中,很多情况下,需要自定义滚动条,比如要实现如下效果:
example.gif
实现思路:横向和纵向列表都是用的RecyclerView,滚动条用ItemDecoration的onDrawOver发放实现
- 横向滚动条关键代码如下:
override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
super.onDrawOver(c, parent, state)
//滚动条拇指的水平范围
val extent=parent.computeHorizontalScrollExtent()
//可滚动的区域大小
val range=parent.computeHorizontalScrollRange()
//当前偏移量(当前滚动的距离)
val offset=parent.computeHorizontalScrollOffset()
//最大偏移量(最大可滚动的距离)
val maxOffset=range-extent
//可以滑动时,在绘制
if (maxOffset>0){
val startX=parent.width/2-scrollBarLength/2
val startY=parent.height-20f.dp2px()
paint.color=Color.parseColor("#f2f2f2")
c.drawLine(startX,startY,startX+scrollBarLength,startY,paint)
paint.color=Color.parseColor("#ff0000")
val ratio=offset.toFloat()/maxOffset.toFloat()
val offsetY=ratio*(scrollBarLength-indicatorLength)
c.drawLine(startX+offsetY,startY,startX+indicatorLength+offsetY,startY,paint)
}
- 纵向滚动条关键代码如下:
override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
super.onDrawOver(c, parent, state)
//滚动条拇指的垂直范围
val extent=parent.computeVerticalScrollExtent()
//可滚动的区域大小
val range=parent.computeVerticalScrollRange()
//当前偏移量(当前滚动的距离)
val offset=parent.computeVerticalScrollOffset()
//最大偏移量(最大可滚动的距离)
val maxOffset=range-extent
//可以滑动时,在绘制
if (maxOffset>0){
val startX=parent.width-10f.dp2px()
val startY=parent.height/2f-scrollBarLength/2f
paint.color=Color.parseColor("#f2f2f2")
c.drawLine(startX,startY,startX,startY+scrollBarLength,paint)
paint.color=Color.parseColor("#ff0000")
val ratio=offset.toFloat()/maxOffset.toFloat()
val offsetY=ratio*(scrollBarLength-indicatorLength)
c.drawLine(startX,startY+offsetY,startX,startY+indicatorLength+offsetY,paint)
}
网友评论