Skip to content

Instantly share code, notes, and snippets.

@jermainedilao
Last active August 6, 2020 08:04
Show Gist options
  • Save jermainedilao/36be149aba70683bce4b5192acc747fe to your computer and use it in GitHub Desktop.
Save jermainedilao/36be149aba70683bce4b5192acc747fe to your computer and use it in GitHub Desktop.
Adds vertical margin to RecyclerView's items. For more information, check this article: https://medium.com/@jermainedilao/android-recyclerview-item-margins-the-right-way-66f8371ee0a1
import android.graphics.Rect
import android.view.View
import androidx.recyclerview.widget.RecyclerView
/**
* Adds vertical margin to RecyclerView's items.
*/
class VerticalMarginItemDecoration(
/**
* Vertical margin for all items.
*/
private val verticalMargin: Int,
/**
* First item top margin.
*/
private val firstItemTopMargin: Int = NOT_SET,
/**
* Last item bottom margin.
*/
private val lastItemMargin: Int = NOT_SET
) : RecyclerView.ItemDecoration() {
companion object {
private const val NOT_SET = -1
}
override fun getItemOffsets(outRect: Rect, view: View, parent: RecyclerView, state: RecyclerView.State) {
with(outRect) {
top = if (isFirstItem(parent, view) && firstItemTopMargin != NOT_SET) {
firstItemTopMargin
} else {
0
}
bottom = if (lastItemMargin == NOT_SET) {
verticalMargin
} else {
if (isLastItem(parent, view, state)) {
lastItemMargin
} else {
verticalMargin
}
}
}
}
private fun isFirstItem(parent: RecyclerView, view: View) =
parent.getChildAdapterPosition(view) == 0
private fun isLastItem(parent: RecyclerView, view: View, state: RecyclerView.State) =
parent.getChildAdapterPosition(view) == state.itemCount - 1
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment