'Add padding on view programmatically

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



Solution 1:[1]

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

Solution 2:[2]

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

Hope that helps!

Solution 3:[3]

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.

Solution 4:[4]

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

view.updatePadding(top = 42)

See docs here

Solution 5:[5]

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.

Solution 6:[6]

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

Solution 7:[7]

use below method for setting padding dynamically

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

Example :

view.setPadding(2,2,2,2);

Solution 8:[8]

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

Solution 9:[9]

Context contect=MainActivity.this;
TextView tview=new TextView(context);
tview.setPaddingRelative(10,0,0,0);

Solution 10:[10]

This image talks for itself, here you can see in which section the padding is applied

enter image description here

Solution 11:[11]

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

Solution 12:[12]

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.

Solution 13:[13]

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

Solution 14:[14]

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

Solution 15:[15]

    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
    }