Created
June 27, 2020 10:46
-
-
Save abhimuktheeswarar/c71eea4be53641cef39805c5ddeb0a74 to your computer and use it in GitHub Desktop.
This decorator adds equal spacing for items in GridLayoutManager
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 com.yourcompany.name | |
import android.graphics.Rect | |
import android.view.View | |
import androidx.recyclerview.widget.GridLayoutManager | |
import androidx.recyclerview.widget.RecyclerView | |
class EqualSpaceItemDecoration(private val padding: Int) : | |
RecyclerView.ItemDecoration() { | |
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) { | |
val layoutParams = view.layoutParams as GridLayoutManager.LayoutParams | |
val gridLayoutManager = parent.layoutManager as? GridLayoutManager | |
val spanSize = layoutParams.spanSize.toFloat() | |
val totalSpanSize = gridLayoutManager!!.spanCount.toFloat() | |
val n = totalSpanSize / spanSize // num columns | |
val c = layoutParams.spanIndex / spanSize // column index | |
val leftPadding = padding * ((n - c) / n) | |
val rightPadding = padding * ((c + 1) / n) | |
outRect.left = leftPadding.toInt() | |
outRect.right = rightPadding.toInt() | |
outRect.bottom = padding | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment