Bobbake4
Bobbake4

Reputation: 24857

How to generate a view id in code?

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?

Upvotes: 1

Views: 446

Answers (3)

Mark
Mark

Reputation: 7728

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.

Upvotes: 0

Kevin Coppock
Kevin Coppock

Reputation: 134714

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.

Upvotes: 0

gianpi
gianpi

Reputation: 3210

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().

Upvotes: 5

Related Questions