为recycleView添加分割线、header和footer
对于recycleView,相信做android的基本都很熟悉 ,我也经常使用,基本把listView、gridView抛弃了(看需求了),但是自己在用的过程中基本都是复制-粘贴、复制-粘贴、复制-粘贴,有些不常用的功能当时可能看好久整明白了,但是过一段时间又给忘了,需要用的时候又得话大把时间去看,浪费精力!今天用的时候涉及到绘制分割线、拖拽item等相关的问题,具体怎么用又给忘了所以又查了点资料复习一遍,然后顺便记下来。。。
recycleView分割线
对于listView、gridView我们可以通过设置divider属性来设置他的分割线,而RecyclerView并没有支持divider这样的属性。当然,如果仅仅只是设置间隙,我们可以通过设置item的布局margin来实现,但是这种方式不够优雅。其实,recyclerView的分割线是可以自由定制的。 在RecyclerView中,Google又为我们提供了ItemDecoration这个类,通过addItemDecoration(RecyclerView.ItemDecoration decor)这个方法可以设置分隔线,那问题又来了,RecyclerView.ItemDecoration是什么东西呢?他是一个抽象类,里面主要有三个方法:
(1)void getItemOffsets ()
(2)void onDraw ()
(3)void onDrawOver ()
getItemOffsets()这个方法设置item偏移量,如果仅仅是设置间隙,只需要重写这个方法就OK了,先看下正常情况下的状态



效果如下:

整个页面浑然一体,现在我们通过重写getItemOffsets()来添加分割线。如下:

复写后的效果如下(这里故意把水平方向上和垂直方向上间距调的不一样)

onDraw()和onDrawOver ()都是用来绘制divider的,onDraw是在itemview绘制之前,onDrawOver是在itemview绘制之后。一般只需重写一个方法即可,所谓文不如表表不如图,单纯的文字可能不好理解,什么绘制之前绘制之后的兼职一脸懵逼,看下图:

效果:

同样的代码放在onDrawOver()里面,运行效果如下,直接截图,就不录gif了

看出差异没?谁在item绘制之前谁在之后是不是一目了然了?
当然,onDrawOver与onDraw同时重写也是可以的,看下图运行效果(所化圆的半径根据需要有改动,方便看出差异)

这样一对比是不是很清楚??这样,我们可以通过重写getItemOffsets和onDraw()(或onDrawOver())来设置各种各样的分割线了
Header 和Footer
RecycleView设置header和footer也很简单,首先定义三个标识为来制定item类别(header还是footer或者普通item)

复写getItemCount(),当没有footer和header时返回数据源大小,header和footer有且只有一个时,返回数据源大小+1,都有事+2,这个地方很重要,注意别写错

复写getItemViewType(),根据有无header、footer的情况返回不同的type

然后根据不同的type create相应的ViewHolder,绑定ViewHolder等等

OK,运行看下效果

尼玛,这是什么鬼,header竟然作为一个cell出现在了界面上,这完全不是我们想要的效果啊!这时我们只需要这样改

在Adapter中再重写一个方法onAttachedToRecyclerView,设置了一个SpanSizeLookup,这个类是一个抽象类,而且仅有一个抽象方法getSpanSize,这个方法的返回值决定了我们每个position上的item占据的单元格个数

嗯,这次正常了,不过对于StaggeredGridLayoutManager,并没有像GridLayoutManager中这样的方法,我们还需要单独为StaggeredGridLayoutManager单独处理一下如下:

这样就OK了,加footer也一样,有兴趣的可以尝试下~~~
封装
adapter里面有很多通用的代码,比如getViewItemType()、getItemCount()以及前面的onAttachedToRecyclerView()、onViewAttachedToWindow()、addHeaderView()、addFooterView()等,我们可以提出来,封装成一个父类,只需在子类复写绑定逻辑就好
添加两个个抽象方法

然后在相应的地方调用

再看看子类如何调用

OK,是不是超级方便?代码似乎也大量减少了,运行效果跟之前一样,木有问题,可以自行尝试
因为一般情况下header和footer在添加前都已经初始化完成了
不需要holder的,所以只写了一个createNormalHolder()方法,header和footer在holder里面没做处理,如果有需要可以再写两个抽象方法


然后在相应的方法里处理自己的逻辑
这样,一个简单的BaseAdapter就封装好并且可以使用了,当然,如果想封装更深的话ViewHolder部分也是可以提取出来的----进一步封装可参考 鸿洋的博客-为RecyclerView打造通用Adapter 让RecyclerView更加好用