Skip to content

Instantly share code, notes, and snippets.

@programmerr47
Created December 28, 2020 12:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save programmerr47/c18040d140e12d6bacfd498e92741644 to your computer and use it in GitHub Desktop.
Save programmerr47/c18040d140e12d6bacfd498e92741644 to your computer and use it in GitHub Desktop.
val View.margin get() = ViewMargin(this)
inline class ViewMargin(private val view: View) {
var start: Int
get() = view.marginStart
set(value) = applyMargin { it.marginStart = value }
var top: Int
get() = view.marginTop
set(value) = applyMargin { it.topMargin = value }
var end: Int
get() = view.marginEnd
set(value) = applyMargin { it.marginEnd = value }
var bottom: Int
get() = view.marginBottom
set(value) = applyMargin { it.bottomMargin = value }
var horizontal: Int
get() = start + end
set(value) {
start = value
end = value
}
var vertical: Int
get() = top + bottom
set(value) {
top = value
bottom = value
}
var total: Int
@Deprecated("No getter for that field", level = DeprecationLevel.HIDDEN)
get() = throw UnsupportedOperationException("No getter for such field")
set(value) {
horizontal = value
vertical = value
}
private inline fun applyMargin(body: (params: ViewGroup.MarginLayoutParams) -> Unit) {
val params = view.layoutParams as? ViewGroup.MarginLayoutParams
if (params != null) {
body(params)
} else {
throw IllegalStateException("Parent layout doesn't support margins")
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment