findViewById not working with ids created using View.generateViewId

425 Views Asked by At

I'm trying to access a view with a dynamically created id, using findViewById but it always returns null.

This is how I'm creating the id, using View.generateViewId() and ViewCompat.generateViewId() for lower API versions.

import androidx.core.view.ViewCompat
import android.view.View

...
// generate an id
val id = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
    View.generateViewId()
} else {
    ViewCompat.generateViewId()
}
// assign the id
view.id = id
// Then add it to a parent view
parent.addView(view)
...

Logging the id gives 3.

Now, the view is getting created, it is visible, there are no errors and even the layout inspector shows the id assigned by the View.generateViewId() to be 0x3 i.e. 3.

image_bruh

val layout = findViewById<LinearLayout>(id)

But the layout is always null.

findViewById returns the LinearLayout successfully when given an id that's defined in ids.xml or the layout/....xml.

It fails only with dynamically created ids.

0

There are 0 best solutions below