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

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


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


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


According to View documentation

The identifier does not have to be unique in this view's hierarchy. The identifier should be a positive number.

So you can use any positive integer you like, but in this case there can be some views with equivalent id's. If you want to search for some view in hierarchy calling to setTag with some key objects may be handy.