Last active
August 6, 2020 08:04
-
-
Save jermainedilao/bee395524ddc6bb410116b74a10bb467 to your computer and use it in GitHub Desktop.
Adds horizontal margin to RecyclerView's items. For more information, check this article: https://medium.com/@jermainedilao/android-recyclerview-item-margins-the-right-way-66f8371ee0a1
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.recyclerview.widget.RecyclerView | |
/** | |
* Adds horizontal margin to RecyclerView's items. | |
*/ | |
class HorizontalMarginItemDecoration( | |
/** | |
* Horizontal margin for all items. | |
*/ | |
private val horizontalMargin: Int, | |
/** | |
* First item left margin. | |
*/ | |
private val firstItemStartMargin: Int = NOT_SET, | |
/** | |
* Last item right margin. | |
*/ | |
private val lastItemEndMargin: 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) { | |
left = if (isFirstItem(parent, view) && firstItemStartMargin != NOT_SET) { | |
firstItemStartMargin | |
} else { | |
horizontalMargin | |
} | |
right = if (lastItemEndMargin == NOT_SET) { | |
horizontalMargin | |
} else { | |
if (isLastItem(parent, view, state)) { | |
lastItemEndMargin | |
} else { | |
horizontalMargin | |
} | |
} | |
} | |
} | |
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