RecyclerView的进阶使用(分割线、拖拽、动画)

前言

使用RecyclerView已经很久了,它相对于ListView和GridView方便很多,使用LayoutManager等类可以给它的使用带来很大的便利。但是后面发现,使用RecyclerView的功能只是那么一小点,也就是都它的基本使用,所以最近对它进一步学习和使用。

添加分割线

RecyclerView默认是没有为我们添加分割线的,这得需要通过自己去实现,虽然看起来麻烦,但是反过来给我们带来更大的灵活性。

思路:

  1. 继承于ItemDecoration类,它是RecyclerView的一个内部类
  2. 定义一个Paint对象,可用于绘制,如果需要的话可提供一些方法供用户设置Paint的属性
  3. 分割线厚度
  4. 重写getItemOffsets方法,此方法可以定义分割线的大小
  5. 重写onDraw方法,此方法在itemView绘制之前调用,所以需要注意绘制后被ItemView覆盖
  6. onDrawOver,此方法在ItemView绘制后调用,可以在此方法上绘制一些覆盖物等的效果

分割线代码:

lass ItemDivider : RecyclerView.ItemDecoration() {
   

    private val mPaint: Paint = Paint(Paint.ANTI_ALIAS_FLAG)

    private var mLayoutManager: RecyclerView.LayoutManager? = null

    var mDividerWidth = 1

    init {
   
        mPaint.style = Paint.Style.FILL
        mPaint.color = 0xff000000.toInt()
    }

    /**
     * 指定分割线的大小
     */
    override fun getItemOffsets(outRect: Rect?, view: View?, parent: RecyclerView?, state: RecyclerView.State?) {
   
        super.getItemOffsets(outRect, view, parent, state)

        if (mLayoutManager == null) {
   
            mLayoutManager = parent?.layoutManager
        }
        
	//根据LayoutManager的类型对应设置分割线
        if (mLayoutManager is LinearLayoutManager) {
   

            val orientation = (mLayoutManager as LinearLayoutManager).orientation

            if (orientation == LinearLayoutManager.VERTICAL) {
   
                outRect?.bottom = mDividerWidth
            } else {
   
                outRect?.right = mDividerWidth
            }

            if (mLayoutManager is GridLayoutManager) {
   

                val layoutParams: GridLayoutManager.LayoutParams? = view?.layoutParams as GridLayoutManager.LayoutParams

                if (orientation == LinearLayoutManager.VERTICAL && layoutParams?.spanIndex!! > 0) {
   
                    outRect?.left = mDividerWidth
                } else if (orientation == LinearLayoutManager.HORIZONTAL && layoutParams?.spanIndex!! > 0) {
   
                    outRect?.top = mDividerWidth
                }

            }
        }

    }

    /**
     * 在ItemView绘制之前调用
     */
    override fun onDraw(c: Canvas?, parent: RecyclerView?, state: RecyclerView.State?) {
   
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值