Created
May 16, 2022 13:08
-
-
Save marius-m/09f5360597dca3e13c30f17b33c83218 to your computer and use it in GitHub Desktop.
Item decorator which can apply offsets to first and last items
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
package lt.markmerkk | |
import android.content.Context | |
import android.graphics.Rect | |
import android.view.View | |
import androidx.recyclerview.widget.RecyclerView | |
import androidx.recyclerview.widget.RecyclerView.ItemDecoration | |
import lt.ermitazas.base.dpToPx | |
/** | |
* Item decorator which can apply offsets to first and last items | |
* Source: https://medium.com/@pa1pal/set-spacing-in-recyclerview-items-by-custom-item-decorator-3312cf489fce | |
* Source: https://gist.github.com/yqritc/ccca77dc42f2364777e1 | |
*/ | |
class ItemOffsetCornerItemsDecoration( | |
private val context: Context, | |
private val offsetItemFirst: Offset = Offset.asEmpty(), | |
private val offsetItemLast: Offset = Offset.asEmpty(), | |
) : ItemDecoration() { | |
override fun getItemOffsets( | |
outRect: Rect, | |
view: View, | |
parent: RecyclerView, | |
state: RecyclerView.State | |
) { | |
super.getItemOffsets(outRect, view, parent, state) | |
val childCount = parent.adapter?.itemCount ?: 0 | |
val childPosition = parent.getChildAdapterPosition(view) | |
when { | |
childPosition == 0 -> { | |
outRect.set( | |
offsetItemFirst.start, | |
offsetItemFirst.top, | |
offsetItemFirst.end, | |
offsetItemFirst.bottom, | |
) | |
} | |
childPosition == childCount - 1 -> { | |
outRect.set( | |
offsetItemLast.start, | |
offsetItemLast.top, | |
offsetItemLast.end, | |
offsetItemLast.bottom, | |
) | |
} | |
} | |
} | |
data class Offset private constructor( | |
val top: Int, | |
val bottom: Int, | |
val start: Int, | |
val end: Int, | |
) { | |
companion object { | |
fun asEmpty(): Offset { | |
return Offset( | |
top = 0, | |
bottom = 0, | |
start = 0, | |
end = 0, | |
) | |
} | |
fun new( | |
top: Int = 0, | |
bottom: Int = 0, | |
start: Int = 0, | |
end: Int = 0, | |
): Offset { | |
return Offset( | |
top = top, | |
bottom = bottom, | |
start = start, | |
end = end, | |
) | |
} | |
fun Offset.withDp(context: Context): Offset { | |
return Offset( | |
top = context.dpToPx(top), | |
bottom = context.dpToPx(bottom), | |
start = context.dpToPx(start), | |
end = context.dpToPx(end), | |
) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment