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