Kotlin Extension Solution
You can add an extension variable like this for each of the specific sides.
inline var View.topPadding: Int
get() = paddingTop
set(@Px value) = setPadding(paddingLeft, value, paddingRight, paddingBottom)
// Then call
myView.topPadding = 10 // px
If you want to use dp
instead of px
, add something like this:
inline var View.rightPaddingDp: Float
get() = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, paddingRight.toFloat(), resources.displayMetrics)
set(value) {
val rightPx = resources.displayMetrics.density * value
setPadding(paddingLeft, paddingTop, rightPx.toInt(), paddingBottom)
}
myView.rightPaddingDp = 10 // dp
To handle horizontal
or vertical
, do something like this. Note that the getter result wouldn't make sense, so you can disable it.
inline var View.horizontalPadding: Int
get() = throw UnsupportedOperationException("No getter for property")
set(@Px value) = setPadding(value, paddingTop, value, paddingBottom)
To use start
or end
and correctly handle RTL languages, you'll need to add this:
inline val View.isLtr get() = SDK_INT < 17 || layoutDirection == View.LAYOUT_DIRECTION_LTR
inline var View.startPadding: Int
get() = if (isLtr) paddingLeft else paddingRight
set(@Px value) {
val left = if (isLtr) value else paddingLeft
val right = if (isLtr) paddingRight else value
setPadding(left, paddingTop, right, paddingBottom)
}
Bonus: Make an equivalent that takes a res
. i.e. topPaddingRes