Reputation: 1370
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?
Upvotes: 1
Views: 3834
Reputation: 36302
These are completely different methods. In fact, setId
is useful to set an ID of a view so that you can use findViewById
later to find it again. You use findViewById
when you know the ID of a view, and you want to get the actual View
object associated with that ID. You use setId
when you already have a View
object, and you want to set an identifier for it, so that later on you can find that same View
object again using findViewById
.
Upvotes: 1
Reputation: 4111
Using findViewById you trying to find view that already "named" and you need to perform some operations after you inflated layout.
Using setId you set up a name for a view (e.g. that was created programmatically) to be able find this view in future by findViewById.
You could use findViewById not only onCreate. Each ViewGroul allow you to find their children by ids.
Upvotes: 1