Android Development
RelativeLayout
Programmatic Layout
Android Views
UI Design

How to lay out Views in RelativeLayout programmatically?

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

RelativeLayout lets Android views position themselves relative to the parent or to sibling views. When you build the layout in code instead of XML, the key pieces are creating IDs, choosing the correct LayoutParams, and adding rules in the right order.

Build the Parent Layout in Code

When you create a RelativeLayout programmatically, the first step is to instantiate the parent and give it layout parameters of its own. After that, every child view must use RelativeLayout.LayoutParams, not LinearLayout.LayoutParams or another subclass.

kotlin
1import android.os.Bundle
2import android.view.View
3import android.widget.Button
4import android.widget.RelativeLayout
5import android.widget.TextView
6import androidx.appcompat.app.AppCompatActivity
7
8class MainActivity : AppCompatActivity() {
9    override fun onCreate(savedInstanceState: Bundle?) {
10        super.onCreate(savedInstanceState)
11
12        val root = RelativeLayout(this).apply {
13            layoutParams = RelativeLayout.LayoutParams(
14                RelativeLayout.LayoutParams.MATCH_PARENT,
15                RelativeLayout.LayoutParams.MATCH_PARENT
16            )
17        }
18
19        setContentView(root)
20    }
21}

That gives you a blank parent container ready to accept children and relative positioning rules.

Always Give Referenced Views an ID

Relative rules such as BELOW, END_OF, or ALIGN_TOP need a real view ID. If you forget to assign one, rules that depend on other views cannot resolve correctly.

kotlin
1val title = TextView(this).apply {
2    id = View.generateViewId()
3    text = "Profile"
4    textSize = 20f
5}
6
7val saveButton = Button(this).apply {
8    id = View.generateViewId()
9    text = "Save"
10}

View.generateViewId() is the easiest safe option when creating views dynamically.

Add Relative Rules With LayoutParams

Each child gets its own RelativeLayout.LayoutParams, and the rules live there. For example, you can center a title and place a button below it.

kotlin
1val titleParams = RelativeLayout.LayoutParams(
2    RelativeLayout.LayoutParams.WRAP_CONTENT,
3    RelativeLayout.LayoutParams.WRAP_CONTENT
4).apply {
5    addRule(RelativeLayout.CENTER_HORIZONTAL)
6    topMargin = 32
7}
8
9val buttonParams = RelativeLayout.LayoutParams(
10    RelativeLayout.LayoutParams.WRAP_CONTENT,
11    RelativeLayout.LayoutParams.WRAP_CONTENT
12).apply {
13    addRule(RelativeLayout.BELOW, title.id)
14    addRule(RelativeLayout.CENTER_HORIZONTAL)
15    topMargin = 24
16}
17
18root.addView(title, titleParams)
19root.addView(saveButton, buttonParams)

This is the core pattern for programmatic RelativeLayout: create the view, create RelativeLayout.LayoutParams, add rules, then attach the view to the parent.

Position Views Relative to the Parent

Some rules refer to the parent instead of another child. Common examples include aligning to the top, bottom, start, or end of the container.

kotlin
1val helpButton = Button(this).apply {
2    id = View.generateViewId()
3    text = "Help"
4}
5
6val helpParams = RelativeLayout.LayoutParams(
7    RelativeLayout.LayoutParams.WRAP_CONTENT,
8    RelativeLayout.LayoutParams.WRAP_CONTENT
9).apply {
10    addRule(RelativeLayout.ALIGN_PARENT_BOTTOM)
11    addRule(RelativeLayout.ALIGN_PARENT_END)
12    bottomMargin = 32
13    marginEnd = 32
14}
15
16root.addView(helpButton, helpParams)

This is useful for floating actions, status labels, or footer controls that should stay pinned to an edge.

Convert Density-Independent Spacing

One easy mistake is hard-coding raw pixel values. Android layouts should usually work in density-independent units, even when built in code.

kotlin
1fun Int.dp(view: View): Int =
2    (this * view.resources.displayMetrics.density).toInt()
3
4titleParams.topMargin = 16.dp(title)
5buttonParams.topMargin = 12.dp(saveButton)

That keeps spacing consistent across devices with different screen densities.

Know When RelativeLayout Is the Wrong Tool

RelativeLayout still works, but many modern Android UIs are easier to manage with ConstraintLayout, especially when the relationships become complex. If your layout starts accumulating many sibling-to-sibling rules, programmatic RelativeLayout can become hard to read and debug.

Still, for a small dynamic form or a couple of anchored buttons, it remains perfectly reasonable.

Common Pitfalls

The biggest mistake is forgetting IDs on views that other rules reference. If a child has no ID, rules like BELOW and END_OF have nothing stable to target.

Another common problem is using the wrong layout params type. A child inside RelativeLayout must receive RelativeLayout.LayoutParams, or the positioning rules will not apply.

Hard-coded pixel margins are another source of bad layouts. Convert spacing from dp so the UI looks consistent across screen densities.

Finally, watch layout complexity. RelativeLayout is convenient for a few relationships, but a heavily dynamic screen may be easier to express with ConstraintLayout or Compose.

Summary

  • Create the parent RelativeLayout first, then add child views with RelativeLayout.LayoutParams.
  • Assign IDs with View.generateViewId() before referencing sibling views in rules.
  • Use addRule to position children relative to the parent or to other children.
  • Convert margins from dp instead of hard-coding raw pixels.
  • Prefer a newer layout system if the rule graph becomes too complex.

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.