Get Lazier with Kotlin - by not declaring UI elements
kotlin ·In my previous post, I spoke briefly about the key differences between Java and Kotlin. In this yet another post I will be talking about a magical plugin of Kotlin for Android.
Let’s make our lives easier and let’s get lazier (If you are like me :P). What If I told you that we don’t have to use findViewById in kotlin for declaring UI elements in our Kotlin class that we have created in the XML. No, I’m not talking about binding libraries like ButterKnife.
I am talking about a plugin called “kotlin-android-extensions” which helps us eliminate declaration of a Variable in our Activity/Fragment/Views altogether and helps us access the element from the XML using the ID itself as a variable!
Let’s see it in action:
Firstly, In our build.gradle file we need to apply the following plugins:
Secondly, we see the magic happen. Let us consider an XML called activity_hello.xml for an Activity called HelloActivity.kt with a textView as follows:
In the HelloActivity.kt, let’s use helloTV without declaring it :D
That’s it! We didn’t have to declare a variable of type TextView and then link it to it’s XML definition using findViewById, thanks to this magical plugin.
However, do note that you are importing this in your activity (Don’t worry if you have auto-import enabled.)
The best part, Kotlin-Android-Extensions is also mentioned in the Offical docs! Reference, Kotlin docs.