E X T E N S I O N S

Get Lazier with Kotlin - by not declaring UI elements

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:

apply plugin: 'com.android.application' //Already exists
apply plugin: 'kotlin-android'          //Exists if you've started off with Kotlin
apply plugin: 'kotlin-android-extensions'  //This is the magical plugin

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:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
     <TextView
        android:id="@+id/helloTV"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Hello!"/>
</RelativeLayout>

In the HelloActivity.kt, let’s use helloTV without declaring it :D

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_hello)
 
    helloTV.text = "Hello Kotlin!" //I honestly did not create the variable in my Kotlin class :P

}

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

import kotlinx.android.synthetic.main.activity_hello.*

The best part, Kotlin-Android-Extensions is also mentioned in the Offical docs! Reference, Kotlin docs.