Android: set just one padding of textview programmatically
use
yourTextView.setPadding(0, 10, 0, 0);
Adjust only the parameters you need and set the other ones to zero.
If you need to preserve other existing paddings, use yourView.getPaddingLeft()
, yourView.getPaddingTop()
and so on.
I usually create a simple utility method just to not forget, or misplace the other paddings:
public static void setPaddingLeft(View v, int leftPaddingDp) { int leftPaddingPx = dpToPx(leftPaddingDp); v.setPadding(leftPaddingPx, v.getPaddingTop(), v.getPaddingRight(), v.getPaddingBottom());}
To be used later like this, supplying dp units, as if would in xmls:
Utils.setPaddingLeft(myExampleTextView, 10)
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 callmyView.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_LTRinline 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