findViewById - Internals
Siddhant Mishra
Senior Android Developer at Teachmint | Kotlin and Java | DSA - 300+ on Leetcode | I read and write about Android and DSA
Hope everyone is doing well.
Today I will be writing about the internal working of findViewById in Android.
I am sure, we all have used findViewById extensively in our Android projects to get access to a certain view in 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
Hey Siddhant, as a fellow Android dev, it's always good to keep options open. Check out Mirajobs for exploring new opportunities without any risk to your current role. It's a great way to stay ahead, especially with the tech market being so unpredictable lately.
Android Developer | 3+ Years' Experience | Proficient in Jetpack Compose, App Security & Performance
1 个月Interesting