I just wrote an answer for someone confused by findViewById and I realised that I have a gap in my understanding. This question is for knowledge and curiosity only.
Consider this:
button = (Button)findViewById(R.id.button);
findViewById
returns an instance of View
, which is then cast to the target class. All good so far.
To setup the view, findViewById
constructs an AttributeSet
from the parameters in the associated XML declaration which it passes to the constructor of View
.
We then cast the View
instance to Button
.
How does the AttributeSet
get passed in turn to the Button
constructor?
[EDIT]
So I was the confused one :). The whole point is that when the layout is inflated, the view hierarchy already contains an instance of the view descendant class. findViewById simply returns a reference to it. Obvious when you think about it - doh..
FindViewById(Int32)Finds a view that was identified by the android:id XML attribute that was processed in #onCreate .
The findViewById() method is a method of Android's View and Activity classes. The method is used to find an existing view in your XML layout by its android:id attribute. The same can be done for any valid Android View object, such as a Button or a CheckBox view.
It's basically a simple loop, I know it's recursive so you'll pay the penalty of constantly switching the stack, but even the most complicated screen is going to be in the order of dozens of Views not thousands, except for recycled lists.
FindViewById can be null if you call the wrong super constructor in a custom view. The ID tag is part of attrs, so if you ignore attrs, you delete the ID.
findViewById
does nothing. It just looks through view hierarchy and returns reference to a view with requested viewId
. View
is already created and exists. If you do not call findViewById
for some view nothing changes.
Views are inflated by LayoutInflator
. When you call setContentView
xml layout is parsed and view hierarchy is created.
attributes passed to Button's constructor by LayoutInflater
. check LayoutInflator source code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With