Skip to content

Instantly share code, notes, and snippets.

@kibotu
Last active September 13, 2023 05:45
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kibotu/60ab145cff5cd0aa95557217d8940c99 to your computer and use it in GitHub Desktop.
Save kibotu/60ab145cff5cd0aa95557217d8940c99 to your computer and use it in GitHub Desktop.
Kotlin extension method to set margin.
fun View.setMargins(
left: Int? = null,
top: Int? = null,
right: Int? = null,
bottom: Int? = null
) {
val lp = layoutParams as? ViewGroup.MarginLayoutParams
?: return
lp.setMargins(
left ?: lp.leftMargin,
top ?: lp.topMargin,
right ?: lp.rightMargin,
bottom ?: lp.bottomMargin
)
layoutParams = lp
}
@Tgo1014
Copy link

Tgo1014 commented Mar 9, 2019

Works really well. Thanks.

@hjiee
Copy link

hjiee commented Dec 14, 2019

Thanks!😁

@darek607
Copy link

bottom ?: lp.bottomMargin

@kibotu
Copy link
Author

kibotu commented May 7, 2021

right oops my bad :D

@Skyrel74
Copy link

Skyrel74 commented Nov 9, 2022

Thank you for your code

@prakashpro3
Copy link

prakashpro3 commented Sep 13, 2023

Thanks. Need to add start margin and end margin.

fun View.setMargins(
        left: Int? = null,
        top: Int? = null,
        right: Int? = null,
        bottom: Int? = null
    ) {
        val lp = layoutParams as? ViewGroup.MarginLayoutParams
            ?: return

        lp.setMargins(
            left ?: lp.leftMargin,
            top ?: lp.topMargin,
            right ?: lp.rightMargin,
            bottom ?: lp.bottomMargin
        )
        lp.marginStart = lp.leftMargin
        lp.marginEnd = lp.rightMargin

        layoutParams = lp
    }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment