Add padding on view programmatically Add padding on view programmatically android android

Add padding on view programmatically


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


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().densityint paddingPixel = (int)(paddingDp * density);view.setPadding(0,paddingPixel,0,0);

Hope that helps!


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.