Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class ItemOffsetDecoration(@DimenRes val offsetId: Int) : RecyclerView.ItemDecoration() {
- override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
- super.getItemOffsets(outRect, view, parent, state)
- val offset = view.context.resources.getDimensionPixelSize(offsetId)
- val position = parent.getChildAdapterPosition(view)
- val items = parent.adapter?.itemCount ?: 0
- if (parent.layoutManager is GridLayoutManager) {
- val columns = (parent.layoutManager as GridLayoutManager).spanCount
- val rows = (items / columns)
- val column = getColumn(position, columns)
- val row = getRow(position, columns)
- val topOffset = if (row == 1) offset else offset / 2
- val leftOffset = if (column == 1) offset else offset / 2
- val bottomOffset = if (row == rows) offset else offset / 2
- val rightOffset = if (column == columns) offset else offset / 2
- outRect.set(leftOffset, topOffset, rightOffset, bottomOffset)
- } else if (parent.layoutManager is LinearLayoutManager) {
- val top = if (position > 0) 0 else offset
- outRect.set(offset, top, offset, offset)
- }
- }
- private fun getRow(position: Int, columns: Int) =
- Math.ceil((position.toDouble() + 1.0) / columns.toDouble()).toInt()
- private fun getColumn(position: Int, columns: Int) = (position % columns) + 1
- }
Add Comment
Please, Sign In to add comment