📌 Layout Margin dp 단위 변경하기
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()
📍 사용 시
layout_example.margin(top = 20F)
'Android > Kotlin' 카테고리의 다른 글
[Kotlin] 함수형 프로그래밍 (0) | 2020.01.06 |
---|---|
[Kotlin] Coroutine 연습 문제 (0) | 2020.01.03 |
[Android/kotlin] ktlint 설치 (0) | 2019.11.18 |
[Android] Retrofit With Coroutine (In MVVM Architecture) (5) | 2019.08.22 |
Android Coroutine 정리 (0) | 2019.08.22 |