Skip to content

Instantly share code, notes, and snippets.

@kibotu
Last active September 13, 2023 05:45
Show Gist options
  • 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
}
@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