findViewById internals in Android

Hope everyone is doing well.
Today, I will delve into the internal workings of findViewById in Android.
We have all extensively used findViewById in our Android projects to access specific views within our layout hierarchy.
It all starts from this -
Tracking the flow further it goes to this in AppCompatActivity -
Further it goes to this point in AppCompatDelegateImpl-
Over here it performs an important action before delegating the task further, it performs something called ensureSubDecor(). This method basically ensures that the basic views for the screen have been rendered before accessing a view on the screen. This might come to our rescue when we lazily inflate our layout and using findViewById to access its views for the first time.
Moving further, the Window's findViewById() is called -
And then finally the View's findViewById() is called -
Over here, something interesting happens. It checks if the id of the current view matches the one we are searching for. In case it matches it returns the view else it does a traversal as mentioned in the above code named findViewTraversal(). Check below for its implementation-
Now the issue is it just checks if the current id matches the searched id, what if the searched view is the one among its children ?
So the final implementation for it is mentioned in the findViewTraversal() inside the ViewGroup class -
It uses a popular Graph traversal technique called DFS(Depth first search), where it checks itself first. If it matches it returns the view else it iterates over its children and checks the same recursively.
Hope you learnt something new today, do follow me for more such content.
Thanks
Subscribe to my newsletter
Read articles from Siddhant Mishra directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
