How findViewById initializes a view

I just wrote an answer for someone confused by findViewById, and I realized that I have a gap in my understanding. This question only concerns knowledge and curiosity.

Consider this:

button = (Button)findViewById(R.id.button); 

findViewById returns an instance of View , which is then discarded to the target class. All is good so far.

To customize the view, findViewById creates an AttributeSet from the parameters of the associated XML declaration that is passed to the View constructor.

Then we apply the View instance to the Button .

How to pass AttributeSet in turn to Button constructor?

[EDIT]

So I was confused :). The thing is that when the layout is inflated, the view hierarchy already contains an instance of the view child class. findViewById just returns a link to it. Obviously, when you think about it - doh ..

+8
android
Feb 10 '13 at 18:22
source share
2 answers

findViewById does nothing. It simply browses the view hierarchy and returns a link to the view with the requested viewId . View already created and exists. If you do not call findViewById for some kind, nothing changes.

Views are bloated on LayoutInflator . When you call setContentView , the xml layout is setContentView and the view hierarchy is created.

passed to the Button constructor using LayoutInflater . Source code of LayoutInflator .

+10
Feb 10 '13 at 18:26
source share

I do not think findViewById() creates or creates an instance of the view. It will search the view hierarchy for an already bloated layout for a view with a matching identifier. This method works differently for View and for ViewGroup .

from Android Source Code:

View.findViewById() returns the same View object, if this view has the given identifier or null, it calls:

 protected View findViewTraversal(int id) { if (id == mID) { return this; } return null; } 

ViewGroup.findViewById() iterates through the child views and calls the same method in these Views, it calls:

  protected View findViewTraversal(int id) { if (id == mID) { return this; } final View[] where = mChildren; final int len = mChildrenCount; for (int i = 0; i < len; i++) { View v = where[i]; if ((v.mPrivateFlags & IS_ROOT_NAMESPACE) == 0) { v = v.findViewById(id); if (v != null) { return v; } } } return null; } 
+5
Feb 10 '13 at 18:33
source share



All Articles