Skip to content

Instantly share code, notes, and snippets.

@marius-m
Created May 20, 2022 09:08
Show Gist options
  • Save marius-m/c533818fdabc0d461c5b9bf20a577ac8 to your computer and use it in GitHub Desktop.
Save marius-m/c533818fdabc0d461c5b9bf20a577ac8 to your computer and use it in GitHub Desktop.
Dynamically apply margin to view. Useful in RecyclerView items when composing complex views
/**
* Dynamically applies margin
*/
fun View?.applyMargin(
marginStart: Int? = null,
marginEnd: Int? = null,
marginTop: Int? = null,
marginBottom: Int? = null,
) {
if (this !is ViewGroup) {
return
}
val lp = this.layoutParams
if (lp is ViewGroup.MarginLayoutParams) {
lp.marginStart = marginStart ?: lp.marginStart
lp.marginEnd = marginEnd ?: lp.marginEnd
lp.topMargin = marginTop ?: lp.topMargin
lp.bottomMargin = marginBottom ?: lp.bottomMargin
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment