Created
May 27, 2024 21:49
-
-
Save ozgurg/99923a188b323f3913f35dfd6d9625f9 to your computer and use it in GitHub Desktop.
Android RecyclerView Item Decoration : Equal Margin + Auto Span Count + Auto Orientation
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
import android.graphics.Rect | |
import android.view.View | |
import androidx.annotation.Px | |
import androidx.recyclerview.widget.GridLayoutManager | |
import androidx.recyclerview.widget.RecyclerView | |
class MarginItemDecoration( | |
@Px private val marginInPixels: Int | |
) : RecyclerView.ItemDecoration() { | |
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { | |
val spanCount = getSpanCount(parent) | |
val orientation = getOrientation(parent) | |
val position = parent.getChildAdapterPosition(view) | |
val isFirstRow = position < spanCount | |
val isStartOfRow = position % spanCount == 0 | |
with(outRect) { | |
if (orientation == RecyclerView.VERTICAL) { | |
top = if (isFirstRow) marginInPixels else 0 | |
left = if (isStartOfRow) marginInPixels else 0 | |
} else if (orientation == RecyclerView.HORIZONTAL) { | |
left = if (isFirstRow) marginInPixels else 0 | |
top = if (isStartOfRow) marginInPixels else 0 | |
} | |
right = marginInPixels | |
bottom = marginInPixels | |
} | |
} | |
private fun getSpanCount(recyclerView: RecyclerView): Int { | |
return (recyclerView.layoutManager as? GridLayoutManager)?.spanCount ?: 1 | |
} | |
@RecyclerView.Orientation | |
private fun getOrientation(recyclerView: RecyclerView): Int { | |
return (recyclerView.layoutManager as? GridLayoutManager)?.orientation ?: RecyclerView.VERTICAL | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment