Goodbye findViewById, say hello to Synthetic Binding
Since the beginning of Android, developers are constantly on a never ending struggle to get rid of redundant and repetitive code that we need to write, thanks partly to the Android Framework.
One such piece of code which is very dear to our hearts (not!) is findViewById()
.
The story of findViewById()
starts with the dawn of Android and it has stuck with us ever since.
More annoying than the thousand times that we have to write it, is the explicit type casting that we had to do because the method returned a View object.
Thankfully this long awaited feature was finally implemented in SDK 26 and we no longer need to typecast the return type of findViewById()
, it infers it automatically. (Yay!)
BUT, that’s not all, we still need to call findViewById()
over and over again. (I typed it 4 times so far in this article :/)
What more can we do to get rid of this as well?
Well, that’s where things start to get interesting with Kotlin and a very nifty feature of the Kotlin-Extensions plugin, known as Synthetic Binding.
Want to know why? Well let’s take an example :
Let’s consider the following xml layout :
Now, to access each View in Java, the traditional approach is :
Enter Kotlin !
So you can see, that I can directly access the view class using it’s ID and that’s it!
Same thing applies to the Adapter’s ViewHolder as well :
So the question that would normally arise in everyone’s mind is,
“So what’s this? Some sort of Black Magic?”
Well, it’s nothing magical, if you decompile the bytecode (By going toTools -> Kotlin -> Show Kotlin Bytecode
and then selecting Decompile
in the pane) and take a look at the generated java class, you’ll see that all it does is call findViewById()
for us.
“What about the performance?”
As mentioned in the official docs of Kotlin Android Extensions :
Invoking
findViewById()
can be slow, especially in case of huge view hierarchies, so Android Extensions tries to minimizefindViewById()
calls by caching views in containers.By default, Android Extensions adds a hidden cache function and a storage field to each container (
Activity
,Fragment
,View
or aLayoutContainer
implementation) written in Kotlin. The method is pretty small so it does not increase the size of APK much.
So I think that it’s a good idea to use Synthetic Binding even if you are only concerned with improving the performance in your app.
“Alright, I’m sold! how do I implement it?”
All you need is to enable the Android Extensions Gradle plugin in your module’s build.gradle
file:
apply plugin: 'kotlin-android-extensions'
That’s it! I hope you liked this post. If you did, don’t forget to 👏.
Bye!
Have feedback? Let’s connect on Twitter.