Last active
May 20, 2022 08:12
-
-
Save marius-m/f36795c2591be946d65f16c307c7adde to your computer and use it in GitHub Desktop.
ItemDecorator for RecyclerView + no decorator on the last item + offset for decorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DividerItemWithoutLastDecoration( | |
val divider: Drawable, | |
val dividerOffset: ItemDecoratorOffset = ItemDecoratorOffset.asEmpty(), | |
) : RecyclerView.ItemDecoration() { | |
override fun onDrawOver(canvas: Canvas, parent: RecyclerView, state: RecyclerView.State) { | |
val dividerLeft = parent.paddingLeft + dividerOffset.start | |
val dividerRight = parent.width - parent.paddingRight - dividerOffset.end | |
val childCount = parent.childCount | |
for (i in 0..childCount - 2) { | |
val child = parent.getChildAt(i) | |
val params = child.layoutParams as RecyclerView.LayoutParams | |
val dividerTop = child.bottom + params.bottomMargin + dividerOffset.top | |
val dividerBottom = dividerTop + divider.intrinsicHeight | |
divider.setBounds(dividerLeft, dividerTop, dividerRight, dividerBottom) | |
divider.draw(canvas) | |
} | |
} | |
override fun getItemOffsets( | |
outRect: Rect, | |
view: View, | |
parent: RecyclerView, | |
state: RecyclerView.State | |
) { | |
super.getItemOffsets(outRect, view, parent, state) | |
if (!isLastItem(parent, view)) { | |
outRect.set( | |
0, | |
0, | |
0, | |
dividerOffset.top + dividerOffset.bottom, | |
) | |
} | |
} | |
private fun isLastItem( | |
parent: RecyclerView, | |
itemView: View, | |
): Boolean { | |
val childCount = parent.adapter?.itemCount ?: 0 | |
val childPosition = parent.getChildAdapterPosition(itemView) | |
return childPosition == childCount - 1 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment