I need to create some views in code and want to assign an id for the view. How can I generate a view id that is guaranteed to be unique among the rest of the view ids but do this at runtime?
Asked
Active
Viewed 398 times
3 Answers
5
IDs of Views don't need to be unique across the whole application, but only in the view hierarchy. With that said, if you want it to be unique, maybe you can use hashCode() and then pass it to View.setID().

gianpi
- 3,110
- 1
- 17
- 13
-
What if this returns the same id as a view that is already defined in that activity? Will this cause a crash? – Bobbake4 Nov 30 '11 at 21:59
-
I don't think it would crash, because if you set the same ID on two views in XML you only get it once in R.java, and still the application will work (however you might get unexpected behaviour when trying to access one of them, i.e. I have no idea if it would get one of them randomly or what). However I think the chances are close to zero, since you should have a view *in the same view hierarchy* that happens to have the same id as the hashcode of another View. – gianpi Nov 30 '11 at 22:03
-
I ended up using the hashCode and I haven't had any issues yet so hope it is fine. Thanks – Bobbake4 Dec 01 '11 at 18:19
0
If you only need to generate a small fixed number of ids, then you could use some of the R.string.* ids that have already been generated. This should guarantee that you don't conflict with existing view ids.

Mark
- 7,446
- 5
- 55
- 75
0
Just a thought: I'm fairly certain that all auto-generated resource IDs are positive integers, so you could simply assign negative integers as the IDs to anything that you create in code. You could even use gianpi's hashCode()
idea and simply use the inverse of that result.

Kevin Coppock
- 133,643
- 45
- 263
- 274