【发布时间】:2019-12-14 02:49:24
【问题描述】:
我想为Header Type 绘制一个默认的ItemDecoration 到RecycleView。但是每个ViewType 都会显示divider。
自定义装饰:
class DividerDecoration(context: Context, orientation: Int)
: DividerItemDecoration(context, orientation){
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
val position = parent.getChildAdapterPosition(view)
val viewType = parent.adapter!!.getItemViewType(position)
if (viewType == ITEM_VIEW_TYPE_HEADER){
super.getItemOffsets(outRect, view, parent, state)
} else {
outRect.setEmpty()
}
}
}
设置:
val itemDecoration = DividerDecoration(binding.recyclerView.context,
DividerItemDecoration.VERTICAL)
binding.recyclerView.addItemDecoration(itemDecoration)
对为什么会发生这种情况有任何建议吗?
更新
上面的代码是有效的。但有一个错误。启动应用程序后,分隔线出现在所有元素中,然后只出现在正确的元素中。为什么会这样?
【问题讨论】:
-
我不知道 Kotlin(我使用 Java),但我认为您不能只为第一项设置分隔符。
-
@GauravMall 我有
header为每个组按日期 -
哦,好的,我明白了,如果我能提供帮助,我会看看!
-
您是否尝试在
getItemOffsets内部使用parent.adapter.getItemViewType(parent.getChildAdapterPosition(view))?这可能有效 - 我自己还没有尝试过。 -
@GauravMall 你当然可以。
标签: android kotlin android-recyclerview item-decoration