简单说ItemDecoration就是Item的装饰,在Item的四周,我们可以给它添加上自定义的装饰;
(是用Kotlin实现的,如果有需要java版,可留言回复)
ItemDecoration主要就三个方法 : )
getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State){}
onDraw(c: Canvas, parent: RecyclerView, state: RecyclerView.State){}
onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State){}
直接上代码(代码带注释)
1. Activity/Fragment中 : )
创建:
private val testRecyclerAdapter by lazy {
TestRecyclerAdapter()
}
private val linearLayoutManager by lazy {
LinearLayoutManager(context)
}
private val headerDecoration by lazy {
StickyHeaderDecoration(requireContext())
}
赋值:
with(rv_view) {
layoutManager = linearLayoutManager
adapter = testRecyclerAdapter
addItemDecoration(headerDecoration)
}
同步更新数据:
val textData = TextDataUtils().getTestData()
textData.sortBy { it.title }//排序
val list = textData.map { bean -> bean.title }//记录每个item分组标题
headerDecoration.setCategoryList(list)//同步分组标题数据Decoration
testRecyclerAdapter.addAllItems(textData)//同步数据至Adapter
2. 接下来就是实现StickyHeaderDecoration
直接上代码 : )
class StickyHeaderDecoration(context: Context) : RecyclerView.ItemDecoration() {
var hideCategoryHeader: ((isHide: Boolean) -> Unit)? = null
var updateCategoryHeader: ((categoryName: String) -> Unit)? = null
private val paint = Paint(Paint.ANTI_ALIAS_FLAG)
private val colorBg = context.resources.getColor(R.color.primary_purple)
private val colorText = context.resources.getColor(R.color.primary_white)
private val categoryList = mutableListOf()
private val categorySet = mutableSetOf()//记录有多少组子标题
val categoryHeaderMap = mutableMapOf()//记录每组子标题开始