Android Development
LinearLayout
Margins
Programmatic Layout
Mobile UI Design

Set margins in a LinearLayout programmatically

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

To set margins programmatically in a LinearLayout, you need to work with the child view’s layout params, not the parent layout itself. In Android, margins live on ViewGroup.MarginLayoutParams, and for a LinearLayout child that usually means LinearLayout.LayoutParams. The most common bug is setting the wrong layout param type or forgetting to convert density-independent units into pixels.

Create the Right LayoutParams

When you add a view to a LinearLayout in code, create LinearLayout.LayoutParams and call setMargins.

Kotlin example:

kotlin
1val textView = TextView(this).apply {
2    text = "Hello"
3}
4
5val params = LinearLayout.LayoutParams(
6    LinearLayout.LayoutParams.WRAP_CONTENT,
7    LinearLayout.LayoutParams.WRAP_CONTENT
8)
9
10params.setMargins(16, 8, 16, 8)
11textView.layoutParams = params
12
13linearLayout.addView(textView)

This works because the child view is receiving the layout params type expected by its LinearLayout parent.

Convert dp to Pixels

Margin values in Android layout XML are usually expressed in dp, but setMargins expects raw pixels. If you hardcode 16 without conversion, the visual result varies by screen density.

Use a helper:

kotlin
1fun Context.dpToPx(dp: Int): Int {
2    return (dp * resources.displayMetrics.density).toInt()
3}
4
5val params = LinearLayout.LayoutParams(
6    LinearLayout.LayoutParams.WRAP_CONTENT,
7    LinearLayout.LayoutParams.WRAP_CONTENT
8)
9
10params.setMargins(
11    dpToPx(16),
12    dpToPx(8),
13    dpToPx(16),
14    dpToPx(8)
15)

This is the correct way to make programmatic margins visually match your XML-based layout expectations.

Update Margins on an Existing View

If the view already exists, read its current layout params, cast them, and then update the margins:

kotlin
val params = myView.layoutParams as LinearLayout.LayoutParams
params.setMargins(dpToPx(24), dpToPx(12), dpToPx(24), dpToPx(12))
myView.layoutParams = params

Reassigning layoutParams helps ensure the view is remeasured and redrawn with the updated values.

If you are writing generic utility code, you can also work against ViewGroup.MarginLayoutParams when the parent type is not fixed up front. The key idea stays the same: margins belong to the child’s layout params object, not to the LinearLayout itself.

Use Start and End Margins for Direction-Aware Layouts

If your app supports right-to-left layouts, marginStart and marginEnd can be more appropriate than left and right margins.

kotlin
1val params = myView.layoutParams as LinearLayout.LayoutParams
2params.marginStart = dpToPx(16)
3params.marginEnd = dpToPx(16)
4params.topMargin = dpToPx(8)
5params.bottomMargin = dpToPx(8)
6myView.layoutParams = params

This respects layout direction better than hardcoding left and right values.

Margins and Existing XML Values

If a view already has XML margins, your programmatic update replaces those runtime values. That can be useful, but it also means you should update all four sides deliberately instead of assuming the old values will remain untouched. Reading the existing params first and then modifying only the sides you want is often the safest pattern.

Java Version

If you are working in Java instead of Kotlin, the same idea applies:

java
1TextView textView = new TextView(this);
2textView.setText("Hello");
3
4LinearLayout.LayoutParams params =
5    new LinearLayout.LayoutParams(
6        LinearLayout.LayoutParams.WRAP_CONTENT,
7        LinearLayout.LayoutParams.WRAP_CONTENT
8    );
9
10params.setMargins(32, 16, 32, 16);
11textView.setLayoutParams(params);
12
13linearLayout.addView(textView);

The underlying API is the same. Only the syntax changes.

Common Pitfalls

One common mistake is casting to the wrong layout params type. If the parent is a LinearLayout, the child should use LinearLayout.LayoutParams, not RelativeLayout.LayoutParams or another unrelated class.

Another mistake is treating raw integers as dp. setMargins expects pixels, so density conversion matters.

Developers also sometimes update the margins on a temporary params object and forget to put it back on the view. Reassigning the updated params is a safer pattern.

Finally, remember that margins belong to the child view’s layout params. Padding is different; padding is space inside the view, not outside it.

Summary

  • Set margins programmatically by editing the child view’s LinearLayout.LayoutParams.
  • Convert dp values to pixels before passing them to setMargins.
  • Cast existing layout params before updating margins on a view already in the layout.
  • Use start and end margins when layout direction matters.
  • Do not confuse margins with padding or with the parent layout’s own spacing.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.