1.作用
1.效果图
item的top,bottom,right,left都是0
2.代码
1.关键代码
// 设置RecycleView的item间的间距,上下间距为20排序,左右间距为20排序
binding.rv.addItemDecoration(object : RecyclerView.ItemDecoration() {
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val position = parent.getChildAdapterPosition(view) // 获取item的位置
val spanCount = 2 // 列数
val itemCount = parent.adapter?.itemCount ?: 0 // item总数
val spacing = 20 // 间距
val row = position / spanCount // 行号
val lastRow = (itemCount - 1) / spanCount // 最后一行的行号
//如果是第一列就设置right,如果是第二列就设置left就好了
if (position%spanCount==0){
outRect.right=20
}else{
outRect.left=20
}
if (row == 0) {
// 如果是第一行,不设置上间距
outRect.top = 0
} else {
// 否则,设置上间距为20
outRect.top = spacing
}
if (row == lastRow) {
// 如果是最后一行,不设置下间距
outRect.bottom = 0
} else {
// 否则,设置下间距为20
outRect.bottom = spacing
}
}
})
2.大概代码
// 创建一个列表,用于存储数据
val itemList = listOf(
Item(