Add padding on view programmatically
Asked Answered
R

15

309

I am developing Android v2.2 app.

I have a Fragment. In the onCreateView(...) callback of my fragment class, I inflate an layout to the fragment like below:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.login, null);
        
    return view;
}

The above inflated layout file is (login.xml):

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Username" />

    
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Username" />

</LinearLayout>

I would like to set a paddingTop to the above <LinearLayout> element , and I want to do it in the Java code instead of do it in xml.

How to set paddingTop to <LinearLayout> in my fragment Java class code ??

Razzledazzle answered 13/3, 2012 at 14:8 Comment(3)
You'll need to assign an ID to your LinearLayout so that you could find it with findViewByIdand then call setPadding on it.Haynes
@AleksG In general yes, but given that the LinearLayout is the root element of the inflated hierachy that's not neccessary here. view is already the LinearLayout, no need to find it again in this case. Given this is a special one though.Lenee
@alextsc: yes, agree. Nevertheless, I still prefer to assign ID's to anything that I may refer to in the application.Haynes
T
581

view.setPadding(0,padding,0,0);

This will set the top padding to padding-pixels.

If you want to set it in dp instead, you can do a conversion:

float scale = getResources().getDisplayMetrics().density;
int dpAsPixels = (int) (sizeInDp*scale + 0.5f);
Tapetum answered 13/3, 2012 at 14:11 Comment(4)
@Razzledazzle as Chris says, it's pixels. If you want dp you'll have to do the conversion manually: float scale = getResources().getDisplayMetrics().density; int size = (int) (sizeInPx*scale + 0.5f);Tapetum
Where is the 0.5f coming from?Weeks
@Georg That code is taken from here: developer.android.com/guide/practices/… The 0.5 is used to get the closest integer when casting (instead of using Math.round())Tapetum
I think the variable names should be the other way around: sizeInDp is actually the number of pixels you get when converting sizeInPx dps.Sugarplum
L
148

To answer your second question:

view.setPadding(0,padding,0,0);

like SpK and Jave suggested, will set the padding in pixels. You can set it in dp by calculating the dp value as follows:

int paddingDp = 25;
float density = context.getResources().getDisplayMetrics().density
int paddingPixel = (int)(paddingDp * density);
view.setPadding(0,paddingPixel,0,0);
Leveille answered 13/3, 2012 at 14:43 Comment(2)
Off course this will compile and work as expected, but for the sake of clarity you should switch the naming of your int variables. Because you define your padding in DP and calculate what it would be in pixels for this given device.Vanillic
You are converting dp to pixel. The variable names are confusing. "paddingPixel" really means dpIdentic
A
115

If you store the padding in resource files, you can simply call

int padding = getResources().getDimensionPixelOffset(R.dimen.padding);

It does the conversion for you.

Acoustician answered 16/9, 2013 at 12:23 Comment(0)
S
74

Using Kotlin and the android-ktx library, you can simply do

view.updatePadding(top = 42)

See docs here

Seventeenth answered 30/10, 2018 at 19:7 Comment(0)
A
20

You can set padding to your view by pro grammatically throughout below code -

view.setPadding(0,1,20,3);

And, also there are different type of padding available -

Padding

PaddingBottom

PaddingLeft

PaddingRight

PaddingTop

These, links will refer Android Developers site. Hope this helps you lot.

Antipope answered 13/3, 2012 at 14:15 Comment(1)
@Razzledazzle Have a look at this one you'll be able to know the difference.Antipope
A
13

Using TypedValue is a much cleaner way of converting to pixels compared to manually calculating:

float paddingDp = 10f;
// Convert to pixels
int paddingPx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, paddingDp, context.getResources().getDisplayMetrics());
view.setPadding(paddingPx, paddingPx, paddingPx, paddingPx);

Essentially, TypedValue.applyDimension converts the desired padding into pixels appropriately depending on the current device's display properties.

For more info see: TypedValue.applyDimension Docs.

Kotlin; extension function

fun Float.px(m: DisplayMetrics!): Int
    get() = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this, m).toInt()

...
val pad = 10.0f.px
Abramabramo answered 4/5, 2017 at 14:49 Comment(2)
shouldn't px and dp be reversed?Lalo
I think the gist of what I am doing is correct. However the naming is confusing I think. I will edit it to be more clear. Thanks for the feedback.Abramabramo
M
10

Use the below method for setting padding dynamically

setPadding(int left, int top, int right, int bottom)

Example:

view.setPadding(2, 2, 2, 2);
Moshemoshell answered 7/9, 2017 at 5:47 Comment(0)
M
7

Here you can see in which section the padding is applied

bidding.subHeader.tvSubHeader.setPadding(0, 5, 0, 0);

Someone edited this answer, but I added an image that had been removed before, here it is again

enter image description here

Momentary answered 15/2, 2022 at 14:48 Comment(0)
L
5

Step 1: First, take the padding value as an integer.

int padding = getResources().getDimensionPixelOffset(R.dimen.padding);

or int padding = 16; [Use any method]

Step 2: Then assign the padding value to the layout.

layout.setPadding(padding, padding, padding, padding);

layout.setPadding(padding_left, padding_top, padding_right, padding_bottom);

All side different padding can be assigned. layout.setPadding(16, 10, 8, 12);

For removing padding (No Padding) set padding values as 0,

layout.setPadding(0, 0, 0, 0);

Lucius answered 19/4, 2022 at 9:51 Comment(0)
N
3

Write Following Code to set padding, it may help you.

TextView ApplyPaddingTextView = (TextView)findViewById(R.id.textView1);
final LayoutParams layoutparams = (RelativeLayout.LayoutParams) ApplyPaddingTextView.getLayoutParams();

layoutparams.setPadding(50,50,50,50);

ApplyPaddingTextView.setLayoutParams(layoutparams);

Use LinearLayout.LayoutParams or RelativeLayout.LayoutParams according to parent layout of the child view

Nothingness answered 13/9, 2016 at 13:46 Comment(1)
setPadding() is not an accessible method from LayoutParams. I'm not sure if it ever was.Franke
A
2
Context context = MainActivity.this;
TextView tView = new TextView(context);
tView.setPaddingRelative(10,0,0,0);
Ascogonium answered 15/7, 2018 at 20:30 Comment(1)
Thank you for this code snippet, which might provide some limited, immediate help. A proper explanation would greatly improve its long-term value by showing why this is a good solution to the problem and would make it more useful to future readers with other, similar questions. Please edit your answer to add some explanation, including the assumptions you’ve made.Cataphoresis
S
1

The best way is not to write your own funcion.

Let me explain the motivaion - please lookup the official Android source code.

In TypedValue.java we have:

    public static int complexToDimensionPixelSize(int data,
            DisplayMetrics metrics)
    {
        final float value = complexToFloat(data);
        final float f = applyDimension(
                (data>>COMPLEX_UNIT_SHIFT)&COMPLEX_UNIT_MASK,
                value,
                metrics);
        final int res = (int) ((f >= 0) ? (f + 0.5f) : (f - 0.5f));
        if (res != 0) return res;
        if (value == 0) return 0;
        if (value > 0) return 1;
        return -1;
    }

and:

    public static float applyDimension(int unit, float value,
                                       DisplayMetrics metrics)
    {
        switch (unit) {
        case COMPLEX_UNIT_PX:
            return value;
        case COMPLEX_UNIT_DIP:
            return value * metrics.density;
        case COMPLEX_UNIT_SP:
            return value * metrics.scaledDensity;
        case COMPLEX_UNIT_PT:
            return value * metrics.xdpi * (1.0f/72);
        case COMPLEX_UNIT_IN:
            return value * metrics.xdpi;
        case COMPLEX_UNIT_MM:
            return value * metrics.xdpi * (1.0f/25.4f);
        }
        return 0;
    }

As you can see, DisplayMetrics metrics can differ, which means it would yield different values across Android-OS powered devices.

I strongly recommend putting your dp padding in dimen xml file and use the official Android conversions to have consistent behaviour with regard to how Android framework works.

Subdivide answered 13/1, 2021 at 17:35 Comment(1)
i want to follow this solution but what to do if the padding is coming as a constant from api?Foment
A
1

Using Jave's solution.

public static int getResourceDimension(Context context, String name, String defType, String defPackage) {
    int sizeInDp = 0;
    int resourceId = context.getResources().getIdentifier(name, defType, defPackage);
    if (resourceId > 0) {
        sizeInDp = context.getResources().getDimensionPixelSize(resourceId);
    }
    float scale = context.getResources().getDisplayMetrics().density;
    int dpAsPixels = (int) (sizeInDp*scale + 0.5f);

    return dpAsPixels;
}

Then call when needed.

int statusBarHeight = getResourceDimension(getContext(), "status_bar_height", "dimen", "android");
statusBarHeight = (int) (statusBarHeight + getResources().getDimension(R.dimen.fragment_vertical_padding));
view.setPadding(0, statusBarHeight, 0, 0);
Apply answered 24/3, 2021 at 10:25 Comment(0)
T
0

While padding programmatically, convert to density related values by converting pixel to Dp.

Tades answered 17/10, 2016 at 13:27 Comment(0)
A
0
    binding.appBarMain.toolbar.setOnApplyWindowInsetsListener { _, insets ->
        val statusBarSize: Int =
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.R) {
                insets.getInsets(WindowInsets.Type.systemBars()).top
            } else {
                insets.systemWindowInsetTop
            }
        binding.appBarMain.appBarLayout.setPadding(0, statusBarSize, 0, 0)
        return@setOnApplyWindowInsetsListener insets
    }
Allative answered 16/2, 2022 at 5:55 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.