Android Development
View ID Assignment
Programmatic UI
Mobile App Development
Android Programming

How can I assign an ID to a view programmatically?

Interview Questions practice on Codemia

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

Browse interview questions

Introduction

When you create Android views at runtime, they do not automatically get a resource ID like views inflated from XML often do. If you need to call findViewById, reference the view from transitions, or save hierarchy state correctly, you should assign a stable ID yourself.

Use View.generateViewId()

For modern Android code, the correct API is View.generateViewId(). It returns an integer that is safe to use as a view ID and avoids collisions with IDs generated from resources.

kotlin
1import android.os.Bundle
2import android.view.View
3import android.widget.Button
4import android.widget.LinearLayout
5import androidx.appcompat.app.AppCompatActivity
6
7class MainActivity : AppCompatActivity() {
8    override fun onCreate(savedInstanceState: Bundle?) {
9        super.onCreate(savedInstanceState)
10
11        val container = LinearLayout(this).apply {
12            orientation = LinearLayout.VERTICAL
13            id = View.generateViewId()
14        }
15
16        val button = Button(this).apply {
17            id = View.generateViewId()
18            text = "Tap me"
19            setOnClickListener {
20                text = "Tapped"
21            }
22        }
23
24        container.addView(button)
25        setContentView(container)
26    }
27}

This is the preferred solution because the platform manages uniqueness for you.

Why IDs Matter for Dynamic Views

You do not need an ID for every runtime-created view. If you already hold a reference to the view, that reference may be enough. IDs become useful when one of these is true:

  • a parent needs to look the view up later
  • layout rules refer to the view by ID
  • state restoration depends on view identity
  • test code or accessibility helpers need stable lookup paths

For example, a ConstraintLayout connection often needs an ID so that constraints can target the correct sibling view.

kotlin
1import android.os.Bundle
2import android.view.View
3import androidx.appcompat.app.AppCompatActivity
4import androidx.constraintlayout.widget.ConstraintLayout
5import androidx.constraintlayout.widget.ConstraintSet
6import android.widget.TextView
7
8class ConstraintExampleActivity : AppCompatActivity() {
9    override fun onCreate(savedInstanceState: Bundle?) {
10        super.onCreate(savedInstanceState)
11
12        val layout = ConstraintLayout(this).apply {
13            id = View.generateViewId()
14        }
15
16        val title = TextView(this).apply {
17            id = View.generateViewId()
18            text = "Dynamic title"
19            textSize = 20f
20        }
21
22        layout.addView(title)
23        setContentView(layout)
24
25        ConstraintSet().apply {
26            clone(layout)
27            connect(title.id, ConstraintSet.TOP, layout.id, ConstraintSet.TOP, 48)
28            connect(title.id, ConstraintSet.START, layout.id, ConstraintSet.START, 32)
29            applyTo(layout)
30        }
31    }
32}

Without a valid ID, those constraints cannot be expressed safely.

Manual IDs Are Rarely Worth It

Older code bases sometimes define constant integers and call setId with those values. That works, but it moves collision management onto you. If two views get the same ID, later lookups become ambiguous and debugging turns into guesswork.

If you need deterministic IDs across process restarts for a generated UI, keep the mapping in one place and document why randomness is not acceptable. Most applications do not need that. They only need unique IDs within the current hierarchy, which generateViewId() already provides.

Compatibility for Older API Levels

If you maintain very old Android versions, View.generateViewId() may not be available directly. In those cases, ViewCompat.generateViewId() from AndroidX is the easy replacement.

kotlin
import androidx.core.view.ViewCompat

val id = ViewCompat.generateViewId()

Using AndroidX keeps the intent clear and avoids reinventing the counter logic with a custom utility.

IDs Versus Tags

Sometimes developers use setTag when they actually need an ID. Tags are useful for attaching metadata or storing an object reference, but they are not a substitute for IDs in layout rules, findViewById, or saved view state.

Use each mechanism for its actual purpose:

  • 'id for structural identity in the view tree'
  • 'tag for associated metadata'

That distinction prevents subtle bugs later when another part of the code assumes the view can be resolved by ID.

Common Pitfalls

The most common mistake is hardcoding small integers such as 1, 2, or 3. Those values may collide with generated resource IDs or with other runtime-assigned IDs.

Another issue is assigning the ID after the code already tried to attach constraints or perform lookups. Set the ID before the view is referenced by anything else.

Some developers also overuse IDs. If a view is private to one method and never looked up later, a direct reference is simpler and clearer.

Finally, do not confuse resource IDs from R.id with generated IDs. Both are valid, but R.id values are defined at build time, while generated IDs are created at runtime.

Summary

  • Use View.generateViewId() for runtime-created Android views.
  • Assign IDs before the view participates in layout rules or lookups.
  • Prefer direct references when no later lookup is needed.
  • Use ViewCompat.generateViewId() when compatibility code requires it.
  • Do not replace IDs with tags when the view needs real structural identity.

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.