Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 994
znq Avatar asked Nov 11 '09 10:11

znq


2 Answers

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

like image 68
X.Y. Avatar answered Oct 22 '22 19:10

X.Y.


You can define the ID's you'll use later in R.id class using an xml resource file, and let Android SDK set the actual unique values during compile time.

 res/values/ids.xml 
<item name="my_edit_text_1" type="id"/> <item name="my_button_1" type="id"/> <item name="my_time_picker_1" type="id"/> 

To use it in the code:

myEditTextView.setId(R.id.my_edit_text_1); 
like image 40
Sai Aditya Avatar answered Oct 22 '22 20:10

Sai Aditya