Home » Android » java – Android: set just one padding of textview programmatically

java – Android: set just one padding of textview programmatically

Posted by: admin April 23, 2020 Leave a comment

Questions:

I want to set the top padding of a textview programmatically. I know you can do this with the method setPadding(). But the problem is that this method requires 4 parameters: left, top, right, bottom. I don’t want to change the left, right and bottom, I just want to change the top padding.

Is that possible?

How to&Answers:

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.

Answer:

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)

Answer:

You can also use this

setPadding(view, 500, Padding.TOP);

with help of a @IntDef definition:

public static void setPadding(View view, int padding, @Padding.Direction int direction) {
    switch (direction) {
        case Padding.LEFT:
            view.setPadding(padding, view.getPaddingTop(), view.getPaddingRight(), view.getPaddingBottom());
            return;
        case Padding.RIGHT:
            view.setPadding(view.getPaddingLeft(), view.getPaddingTop(), padding, view.getPaddingBottom());
            return;
        case Padding.TOP:
            view.setPadding(view.getPaddingLeft(), padding, view.getPaddingRight(), view.getPaddingBottom());
            return;
        case Padding.BOTTOM:
            view.setPadding(view.getPaddingLeft(), view.getPaddingTop(), view.getPaddingRight(), padding);
            return;
        default:
    }
}

public static class Padding {
    @IntDef({Padding.LEFT, Padding.RIGHT, Padding.TOP, Padding.BOTTOM})
    @Retention(RetentionPolicy.SOURCE)
    public @interface Direction {}
    public static final int LEFT = 0;
    public static final int RIGHT = 1;
    public static final int TOP = 2;
    public static final int BOTTOM = 3;
}

Answer:

Below code is working fine.

float scale = getResources().getDisplayMetrics().density;
int dpAsPixels = (int) (sizeInDp*scale + 0.5f);