写一个通用的ItemDecoration,用来给普通的GridLayoutmanageryong用,网格的一般好像都没啥特别的要求,弄个间隔就行了,至于颜色设置recyclerview的就行拉,
参数简单说明下,spacing是默认的间隔,就是说如果水平和垂直方向的间隔一样就设置这个,如果不一样,
可以调用setHVSpace这个单独设置水平垂直方向的间隔,
构造方法里的leftRightDraw用来设置,左右两边是否留间隔,
setTopBottom方法设置上下是否留间隔,就是recyclerview的第一行上边和最后一行的下边是否需要。
如果有特殊需求,比如上下左右边间的间隔和中间的不一样,稍微自己修改下就完事拉。
代码很简单,就不做说明了
import android.graphics.Rect
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
/**
* Created by Sage on 2017/10/12.
* Description:给网格布局用的
* leftRightDraw左右两边是否画间隔
* spacing,默认的水平和垂直的间距是一样的,如果不想一样调用单独的设置方法setHVSpace设置
*/
class ItemDetectorGridHV(var spacing: Int, var leftRightDraw: Boolean) : RecyclerView.ItemDecoration() {
var topDraw=false//第一行顶部和最后一行底部是否要分割
var bottomDraw=false//第一行顶部和最后一行底部是否要分割
fun setTopBottom(topDraw: Boolean,bottomDraw: Boolean): ItemDetectorGridHV {
this.topDraw= topDraw
this.bottomDraw= bottomDraw
return this
}
var spaceH= -1;//水平防线的间隔
var spaceV= -1;//垂直方向的间隔
fun setHVSpace(spaceH: Int,spaceV: Int): ItemDetectorGridHV {
this.spaceH= spaceH
this.spaceV= spaceV
return this
}
override fungetItemOffsets(outRect: Rect,view: View,parent: RecyclerView,state: RecyclerView.State?) {
valmanager = (parent.layoutManager?:return)as?GridLayoutManager ?:return
if(spaceH<0||spaceV<0){
spaceH=spacing
spaceV=spacing
}
valgridLayoutManager = manager
valspanCount = gridLayoutManager.spanCount
valposition = parent.getChildAdapterPosition(view)// item position
valcolumn = position % spanCount// item column
valcount = gridLayoutManager.itemCount
if(count ==0) {
return
}
varrow=position/spanCount
//最后一行的索引,从0开始
vallastRow=(count-1)/spanCount
outRect.left=spaceV/2
outRect.right=spaceV/2
if(column==0){
outRect.left=if(leftRightDraw)spaceVelse0
}
if(column==spanCount-1){
outRect.right=if(leftRightDraw)spaceVelse0
}
outRect.left=spaceV/2
outRect.right=spaceV/2
if(column==0){
outRect.left=if(leftRightDraw)spaceVelse0
}
if(column==spanCount-1){
outRect.right=if(leftRightDraw)spaceVelse0
}
outRect.top=spaceH/2
outRect.bottom=spaceH/2
if(row==0){
outRect.top=if(topDraw)spaceHelse0
}
if(row ==lastRow){
outRect.bottom=if(bottomDraw)spaceHelse0
}
}
}