310

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 ??

Boken
5,46710 gold badges41 silver badges47 bronze badges
asked Mar 13, 2012 at 14:08
3
  • 3
    You'll need to assign an ID to your LinearLayout so that you could find it with findViewByIdand then call setPadding on it. Commented Mar 13, 2012 at 14:13
  • @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. Commented Mar 13, 2012 at 14:20
  • 1
    @alextsc: yes, agree. Nevertheless, I still prefer to assign ID's to anything that I may refer to in the application. Commented Mar 13, 2012 at 14:28

15 Answers 15

584

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);
answered Mar 13, 2012 at 14:11
Sign up to request clarification or add additional context in comments.

@Leem.fin 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);
Where is the 0.5f coming from?
@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())
I think the variable names should be the other way around: sizeInDp is actually the number of pixels you get when converting sizeInPx dps.
149

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);
starball
62.1k60 gold badges355 silver badges1.1k bronze badges
answered Mar 13, 2012 at 14:43

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.
You are converting dp to pixel. The variable names are confusing. "paddingPixel" really means dp
116

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.

Praveenkumar
24.6k23 gold badges101 silver badges177 bronze badges
answered Sep 16, 2013 at 12:23

Comments

76

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

view.updatePadding(top = 42)

See docs here

answered Oct 30, 2018 at 19:07

Comments

22

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.

answered Mar 13, 2012 at 14:15

@Leem.fin Have a look at this one you'll be able to know the difference.
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
Scre
5891 gold badge10 silver badges16 bronze badges
answered May 4, 2017 at 14:49

shouldn't px and dp be reversed?
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.
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);
Aldan
72310 silver badges25 bronze badges
answered Sep 7, 2017 at 5:47

Comments

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

answered Feb 15, 2022 at 14:48

Comments

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);

answered Apr 19, 2022 at 9:51

Comments

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

Praveenkumar
24.6k23 gold badges101 silver badges177 bronze badges
answered Sep 13, 2016 at 13:46

setPadding() is not an accessible method from LayoutParams. I'm not sure if it ever was.
2
Context context = MainActivity.this;
TextView tView = new TextView(context);
tView.setPaddingRelative(10,0,0,0);
Aldan
72310 silver badges25 bronze badges
answered Jul 15, 2018 at 20:30

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.
2

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);
Aldan
72310 silver badges25 bronze badges
answered Mar 24, 2021 at 10:25

Comments

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.

answered Jan 13, 2021 at 17:35

i want to follow this solution but what to do if the padding is coming as a constant from api?
0

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

answered Oct 17, 2016 at 13:27

Comments

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
 }
answered Feb 16, 2022 at 5:55

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.