寫一個通用的ItemDecoration,用來給普通的GridLayoutmanageryong用,網(wǎng)格的一般好像都沒啥特別的要求,弄個間隔就行了,至于顏色設置recyclerview的就行拉,
參數(shù)簡單說明下,spacing是默認的間隔,就是說如果水平和垂直方向的間隔一樣就設置這個,如果不一樣,
可以調(diào)用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:給網(wǎng)格布局用的
* leftRightDraw左右兩邊是否畫間隔
* spacing,默認的水平和垂直的間距是一樣的,如果不想一樣調(diào)用單獨的設置方法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
}
}
}