all throughout the developer documents & tutorials, they reccomend use of findViewById() to “Find a view that was identified by the id attribute from the XML that was processed in onCreate(Bundle)” so i exclusively had been using that everywhere i needed a view to reference something in an xml file. this had caused a number of problems, like if i needed to use a view within a static method, or, as far as i can tell, any method aside from onCreate. recently i stumbled upon setId() which, in addition to being briefer to write and being more readable since it is following the standard “getters & setters” protocol, also seems to have no requirements as to where you use it within your app.
what actually is the difference between:
setId – “Sets the identifier for this view. The identifier does not have to be unique in this view’s hierarchy. The identifier should be a positive number.”
&
findViewById – “Look for a child view with the given id. If this view has the given id, return this view.”
are they interchangeable? are there circumstances that only allow use of one or the other?
These are completely different methods. In fact,
setIdis useful to set an ID of a view so that you can usefindViewByIdlater to find it again. You usefindViewByIdwhen you know the ID of a view, and you want to get the actualViewobject associated with that ID. You usesetIdwhen you already have aViewobject, and you want to set an identifier for it, so that later on you can find that sameViewobject again usingfindViewById.