findViewById with variable

i am very new at Android/Kotlin development and I have a very simple question.
I try to use the “findViewById” expression in combination with a variable. x is a number and counted up.
Here is my snippet:

var my_element = "dot"+x
round = findViewById(

But it doesnt work.
How can I use a dynamic expression in the “findViewById”-function?
Thank you!

you can’t.

Okay, good to know. Thank you.
Is there any possibilty to use a workaround for my question?

Maybe to count the elements in my layout and choose, for example, the third one?

The parameter for findViewById is an int and is a class that provides lots of int constants.

So, technically, it is possible to use (Java) reflection to reach the goal:

There is even a method by Android for it:

However, both ways are discouraged since they are very inefficient.

Therefore, it makes sense to take a second look at your specific case.
E.g., in the special case that you have a fixed number of dot-views, you can use a simple custom array (defined once):

val dotIds = arrayOf(,,
round = findViewById(dotIds[x])

Check out ViewGroup.getChildCount() and ViewGroup.getChildAt().

1 Like