findViewById with variable

Hi,
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(R.id.my_element)

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 R.id 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(R.id.dot0, R.id.dot1, R.id.dot2)
...
round = findViewById(dotIds[x])
2 Likes

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

1 Like