Android: View.setID(int id) programmatically - how to avoid ID conflicts?

znq picture znq · Nov 11, 2009 · Viewed 251.9k times · Source

I'm adding TextViews programmatically in a for-loop and add them to an ArrayList.

How do I use TextView.setId(int id)? What Integer ID do I come up with so it doesn't conflict with other IDs?

Answer

X.Y. picture X.Y. · Mar 15, 2013

From API level 17 and above, you can call: View.generateViewId()

Then use View.setId(int).

If your app is targeted lower than API level 17, use ViewCompat.generateViewId()