0

I need to the margin to the views. I am doing it programmatically by

view.layoutParams = LayoutParams(size, size).apply {
                    topMargin = resources.getDimensionPixelOffset(R.dimen._4sdp)
                }

However, when I test the layout on API 22 the margin does not apply, but in API 28 everything works fine.

  • see this link. i hope it helps you. https://stackoverflow.com/questions/12728255/in-android-how-do-i-set-margins-in-dp-programmatically – Farzad Kamali Apr 06 '20 at 03:50

1 Answers1

0

This is how I would like to do in Kotlin -

fun View.margin(left: Float? = null, top: Float? = null, right: Float? = null, bottom: Float? = null) {
    layoutParams<ViewGroup.MarginLayoutParams> {
        left?.run { leftMargin = dpToPx(this) }
        top?.run { topMargin = dpToPx(this) }
        right?.run { rightMargin = dpToPx(this) }
        bottom?.run { bottomMargin = dpToPx(this) }
    }
}

inline fun <reified T : ViewGroup.LayoutParams> View.layoutParams(block: T.() -> Unit) {
    if (layoutParams is T) block(layoutParams as T)
}

fun View.dpToPx(dp: Float): Int = context.dpToPx(dp)
fun Context.dpToPx(dp: Float): Int = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, resources.displayMetrics).toInt()

now we just have to call this on a view like

textView.margin(left = 16F)
Ravi
  • 2,277
  • 3
  • 22
  • 37