In an XML file, we can assign an ID to a view like android:id="@+id/something"
and then call findViewById()
, but when creating a view programmatically, how do I assign an ID?
I think setId()
is not the same as default assignment. setId()
is extra.
Can anybody correct me?
This question is related to
android
android-view
android-resources
findviewbyid
android-identifiers
You can just use the View.setId(integer)
for this. In the XML, even though you're setting a String id, this gets converted into an integer. Due to this, you can use any (positive) Integer for the Views
you add programmatically.
According to
View
documentationThe 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.
Credits to this answer.
Yes, you can call setId(value)
in any view with any (positive) integer value that you like and then find it in the parent container using findViewById(value)
. Note that it is valid to call setId()
with the same value for different sibling views, but findViewById()
will return only the first one.
Source: Stackoverflow.com