Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does findViewById initialise a view

Tags:

android

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..

like image 398
Simon Avatar asked Feb 10 '13 18:02

Simon


People also ask

What is findViewById () method used for?

FindViewById(Int32)Finds a view that was identified by the android:id XML attribute that was processed in #onCreate .

How does findViewById work on android?

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.

Is findViewById recursive?

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.

Why is findViewById returning NULL?

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.


1 Answers

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.

like image 197
Leonidos Avatar answered Sep 30 '22 00:09

Leonidos