Reputation: 357
I’m getting some data from a REST API (json) from a wordpress.
With theses data, I’m creating some EditText and add the value of the API into the EditText. I want to set an ID so that two of the EditText that I’ve created can be used by each other (for a calcutation : price * quantity)
But when I'm trying to add an id, Android Studio says that it needs to be an int (not like we do in XML, is that the usual comportement ?).
val input = EditText(this)
input.id = id //dynamically equals 5
val test = findViewById<EditText>(5) //5 as ID is not working...
What am I missing on this ?
Upvotes: 0
Views: 3333
Reputation: 1888
This is your example:
val editText = EditText(this)
editText.id = 5
val test = findViewById<EditText>(5)
This doesn't work because '5' is not a valid id, because an id must be an hexadecimal int, and must be different from others views' id. So the better way to achieve your purpose is to do something like this:
val editText = EditText(this)
editText.id = View.generateViewId()
val test = findViewById<EditText>(editText.id)
According to the docs for View.generateViewId()
:
Generate a value suitable for use in setId(int). This value will not collide with ID values generated at build time by aapt for R.id.
But I don't know why you need the "test" EditText, in this way you'll have 2 EditText object that refers to the same View.
Upvotes: 2