additemdecoration重复_RecyclerView ItemDecoration-实现分组/悬浮(粘性)头部

简单说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()//记录每组子标题开始

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值