Skip to content

Instantly share code, notes, and snippets.

@dmitriy-chernysh
Created June 18, 2020 16:14
Show Gist options
  • Save dmitriy-chernysh/b1f0c0fa34e3f04fe28b92b0570ce58e to your computer and use it in GitHub Desktop.
Save dmitriy-chernysh/b1f0c0fa34e3f04fe28b92b0570ce58e to your computer and use it in GitHub Desktop.
class GridRecyclerView : RecyclerView {
private lateinit var manager: GridLayoutManager
private var columnWidth = -1
constructor(context: Context) : super(context) {
init(context, null)
}
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
init(context, attrs)
}
constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(context, attrs, defStyle) {
init(context, attrs)
}
private fun init(context: Context, attrs: AttributeSet?) {
if (attrs != null) {
val attrsArray = intArrayOf(
android.R.attr.columnWidth
)
val array = context.obtainStyledAttributes(attrs, attrsArray)
columnWidth = array.getDimensionPixelSize(0, -1)
array.recycle()
}
manager = GridLayoutManager(getContext(), 1)
layoutManager = manager
}
override fun onMeasure(widthSpec: Int, heightSpec: Int) {
super.onMeasure(widthSpec, heightSpec)
if (columnWidth > 0) {
var spanCount = 1.coerceAtLeast(measuredWidth / columnWidth)
//we need at least 2 columns
if (spanCount == 1) spanCount = 2
manager.spanCount = spanCount
}
}
/**
* Item decoration
*/
class ItemDecoration(context: Context, @DimenRes marginDimenId: Int) : RecyclerView.ItemDecoration() {
private val margin: Int = context.resources.getDimensionPixelSize(marginDimenId)
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: State) {
outRect[margin, margin, margin] = margin
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment