RecyclerView ItemDecoration 原理分析

本文详细介绍了如何自定义RecyclerView的ItemDecoration,通过分析DividerItemDecoration源码,讲解了关键方法onDraw、onDrawOver和getItemOffsets的作用,并提供了自定义分割线样式的实践案例,帮助读者理解和实现自定义布局效果。
摘要由CSDN通过智能技术生成

 

上一篇的例子因为都是不同颜色的图片所以在设置之后能够看见图片之间的分割线,但是如果是纯白色,可能分割线看不出来,又或者需要各种样式(颜色和线条,比如虚线等),那就一定要自定义了,那怎么样去自定义呢?看过下面的分析后我相信对读者会有很大帮助,同时介绍一个个开源项目,大家可以去git上下载下来使用或者修改后使用:

https://github.com/yqritc/RecyclerView-FlexibleDivider

 

1、DividerItemDecoration

上一篇的简单使用中说到可以通过RecyclerView的addItemDecoration(ItemDecoration decor)方法来设置item之间的分割线。SDK目前提供了默认的分割线,在 android.support.v7.widget.DividerItemDecoration,下面是它的源码,看看开始的类注释说明,DividerItemDecoration是一种可用于items之间的分割线,如LinearLayoutManager,支持横向和竖向的。源代码不到200行,很简单,那么我们可以参照这个做一个分割线,并且在网格布局能同时使用横竖分割线,如上篇,可以看效果,或者下载git上的代码,自己修改看看效果,git仓库地址:https://github.com/cmyeyi/smm.git

2、DividerItemDecoration源码

加上注释和类库的引入全部就181行代码,可自行在AS中查看

 

3、自定义ItemDecoration

如何使用DividerItemDecoration,上面可以很简单的看明白,现在开始实践自定义。

自定义ItemDecoration需要继承它,下面是ItemDecoraction的源码,RecyclerView的一个内部类,它是一个抽象类,所有的方法需要我们自己实现,可以参考sdk提供的DividerItemDecoration的源码,甚至能够直接copy过来修改一下,

/**
 * An ItemDecoration allows the application to add a special drawing and layout offset
 * to specific item views from the adapter's data set. This can be useful for drawing dividers
 * between items, highlights, visual grouping boundaries and more.
 *
 * <p>All ItemDecorations are drawn in the order they were added, before the item
 * views (in {@link ItemDecoration#onDraw(Canvas, RecyclerView, RecyclerView.State) onDraw()}
 * and after the items (in {@link ItemDecoration#onDrawOver(Canvas, RecyclerView,
 * RecyclerView.State)}.</p>
 */
public abstract static class ItemDecoration {
    /**
     * Draw any appropriate decorations into the Canvas supplied to the RecyclerView.
     * Any content drawn by this method will be drawn before the item views are drawn,
     * and will thus appear underneath the views.
     *
     * @param c Canvas to draw into
     * @param parent RecyclerView this ItemDecoration is drawing into
     * @param state The current state of RecyclerView
     */
    public void onDraw(Canvas c, RecyclerView parent, State state) {
        onDraw
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值