RecycleView 橫向滑動(dòng)指示器

項(xiàng)目中需要添加類似京東 淘寶首頁(yè)商品滑動(dòng) 下面的指示器跟隨隨便位移對(duì)應(yīng)進(jìn)度。具體效果如下:

Screenshot_2020-06-24-15-15-39-138_com.xueersi.pa.png

具體實(shí)現(xiàn)demo效果:

Screenshot_2020-06-24-15-30-30-516_com.yunlei.hin.png
Screenshot_2020-06-24-15-30-35-924_com.yunlei.hin.png

1、分析

其實(shí)這個(gè)很簡(jiǎn)單,主要就是有以下幾點(diǎn)

  • 1.繪制一個(gè)圓角矩形做背景;
  • 2.繪制一個(gè)圓角矩形做背景;
  • 3 .繪制一個(gè)圓角矩形做指示器;
  • 4.確定指示器的長(zhǎng)度和指示器的位置;
  • 5.根據(jù)RecyclerView滑動(dòng)的距離動(dòng)態(tài)改變指示器的位置。

2、繪制指示器

繪制背景的圓角矩形的時(shí)候,不考慮padding信息,就很簡(jiǎn)單

 override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        viewWidth = w
        mBgRect.set(0f, 0f, w * 1f, h * 1f)
        mRadius = h / 2f
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        //繪制背景
        canvas?.drawRoundRect(mBgRect, mRadius, mRadius, mBgPaint)
    }

繪制指示器

ratio指的是指示器長(zhǎng)度,即如果滾動(dòng)內(nèi)容有兩屏,則指示器應(yīng)該為1/2長(zhǎng)度,以此類推 (當(dāng)然上面所示app不一定實(shí)現(xiàn)了這個(gè),可能會(huì)為了美觀設(shè)置一個(gè)固定比例)

progress指的是滑動(dòng)距離和指示器對(duì)應(yīng)關(guān)系,這個(gè)實(shí)際上就是滑動(dòng)進(jìn)度條的意思

 //計(jì)算指示器的長(zhǎng)度和位置
    val leftOffset = viewWidth * (1f - ratio) * progress
    val left = mBgRect.left + leftOffset
    val right = left + viewWidth * ratio
    mRect.set(left, mBgRect.top, right, mBgRect.bottom)

    //繪制指示器
    canvas?.drawRoundRect(mRect, mRadius, mRadius, mPaint)

3、和RecyclerView聯(lián)動(dòng)

獲取RecyclerView滾動(dòng)的位置可根據(jù)以下幾個(gè)方法獲取

    1. computeVerticalScrollExtent()/computeHorizontalScrollExtent//當(dāng)前RcyclerView顯示區(qū)域的高度。水平列表屏幕從左側(cè)到右側(cè)顯示范圍
    1. computeVerticalScrollOffset()/computeHorizontalScrollOffset //已經(jīng)向下滾動(dòng)的距離,為0時(shí)表示已處于頂部。
    1. computeVerticalScrollRange()/computeHorizontalScrollRange //整體的高度,注意是整體,包括在顯示區(qū)域之外的

監(jiān)聽(tīng)滑動(dòng),配合上訴方法就可以拿到滑動(dòng)位置的比例

 recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)
            val offsetX = recyclerView.computeHorizontalScrollOffset()
            val range = recyclerView.computeHorizontalScrollRange()
            val extend = recyclerView.computeHorizontalScrollExtent()
            val progress: Float = offsetX * 1.0f / (range - extend)     //因?yàn)橹甘酒饔虚L(zhǎng)度,所以這里需要減去首屏長(zhǎng)度
            this@HIndicator.progress = progress     //設(shè)置滾動(dòng)距離所占比例
        }
    })

具體實(shí)現(xiàn)邏輯:


class TreeIndicator @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val mBgPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private val mBgRect: RectF = RectF()
    private var mRadius: Float = 0f
    private val mPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)
    private var mRect: RectF = RectF()
    private var viewWidth: Int = 0
    private var mBgColor = Color.parseColor("#e5e5e5")
    private var mIndicatorColor = Color.parseColor("#ff4646")
    var ratio = 0.5f        //長(zhǎng)度比例
        set(value) {
            field = value
            invalidate()
        }
    var progress: Float = 0f    //滑動(dòng)進(jìn)度比例
        set(value) {
            field = value
            invalidate()
        }

    init {

        val typedArray: TypedArray = context.obtainStyledAttributes(attrs, R.styleable.HIndicator)
        mBgColor = typedArray.getColor(R.styleable.HIndicator_hi_bgColor, mBgColor)
        mIndicatorColor =
            typedArray.getColor(R.styleable.HIndicator_hi_indicatorColor, mIndicatorColor)
        typedArray.recycle()

        mBgPaint.color = mBgColor
        mBgPaint.style = Paint.Style.FILL
        mPaint.color = mIndicatorColor
        mPaint.style = Paint.Style.FILL

    }

    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
        super.onSizeChanged(w, h, oldw, oldh)
        viewWidth = w
        mBgRect.set(0f, 0f, w * 1f, h * 1f)
        mRadius = h / 2f
    }

    /**
     * 設(shè)置指示器背景進(jìn)度條的顏色
     * @param color 背景色
     */
    fun setBgColor(@ColorInt color: Int) {
        mBgPaint.color = color
        invalidate()
    }

    /**
     * 設(shè)置指示器的顏色
     * @param color 指示器顏色
     */
    fun setIndicatorColor(@ColorInt color: Int) {
        mPaint.color = color
        invalidate()
    }

    /**
     * 綁定recyclerView
     */
    fun bindRecyclerView(recyclerView: RecyclerView) {
        recyclerView.addOnScrollListener(object : RecyclerView.OnScrollListener() {
            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
                super.onScrolled(recyclerView, dx, dy)
                val offsetX = recyclerView.computeHorizontalScrollOffset() //已經(jīng)向下滾動(dòng)的距離,為0時(shí)表示已處于頂部。
                val range = recyclerView.computeHorizontalScrollRange()   //整體的高度,注意是整體,包括在顯示區(qū)域之外的
                val extend = recyclerView.computeHorizontalScrollExtent() //當(dāng)前RcyclerView顯示區(qū)域的高度。水平列表屏幕從左側(cè)到右側(cè)顯示范圍
                val progress: Float = offsetX * 1.0f / (range - extend)
                this@HIndicator.progress = progress     //設(shè)置滾動(dòng)距離所占比例

                Log.d("==distance==offsetX",offsetX.toString())
                Log.d("==distance==range",range.toString())
                Log.d("==distance==extend",extend.toString())
                Log.d("==distance==progress",progress.toString())


            }
        })

        recyclerView.addOnLayoutChangeListener { _, _, _, _, _, _, _, _, _ ->
            val range = recyclerView.computeHorizontalScrollRange()
            val extend = recyclerView.computeHorizontalScrollExtent()
            val ratio = extend * 1f / range
            this@HIndicator.ratio = ratio       //設(shè)置指示器所占的長(zhǎng)度比例
        }
    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        //繪制背景
        canvas?.drawRoundRect(mBgRect, mRadius, mRadius, mBgPaint)

        //計(jì)算指示器的長(zhǎng)度和位置
        val leftOffset = viewWidth * (1f - ratio) * progress
        val left = mBgRect.left + leftOffset
        val right = left + viewWidth * ratio
        mRect.set(left, mBgRect.top, right, mBgRect.bottom)

        //繪制指示器
        canvas?.drawRoundRect(mRect, mRadius, mRadius, mPaint)
    }

}
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        recyclerView.adapter = MAdapter()
        hIndicator.bindRecyclerView(recyclerView)


        btn1.setOnClickListener {
            hIndicator.setBgColor(Color.parseColor("#333333"))
        }


        btn2.setOnClickListener {
            hIndicator.setIndicatorColor(Color.parseColor("#ffffff"))
        }
    }

    private inner class MAdapter : RecyclerView.Adapter<MViewHolder>() {
        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MViewHolder =
            MViewHolder(
                LayoutInflater.from(parent.context).inflate(
                    R.layout.item_test,
                    parent,
                    false
                )
            )


        override fun getItemCount(): Int = 15

        override fun onBindViewHolder(holder: MViewHolder, position: Int) {
        }

    }

    private inner class MViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView)
}



    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layoutManager="androidx.recyclerview.widget.GridLayoutManager"
        app:spanCount="2"/>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容