Kotlin-android-extensions: accessing widgets from a Kotlin activity

We no more need findViewById() again , as Kotlin Android Extensions is here . Probably you have used the Butterknife library to avoid writing findViewById() again and again . But with Kotlin Android Extensions plugin its even easier . The process can be summerized in three steps as below :

1. Apply the ‘kotlin-android-extensions’ plugin in app level build.gradle file
apply plugin: ‘kotlin-android-extensions’

2. Add an import statement to make the widgets of the layout file accessible from Kotlin code. The import statement should look like the one below (here activity_main is the layout of our activity)
import kotlinx.android.synthetic.main.activity_main.*

3. All done , the widgets of the layout can now be accessed by their ids .
If there is a TextView in our layout whose text we want to change and tv_hello is its id , then we can use tv_hello to access all members of the textview .
e.g. tv_hello.text = “We don’t need findViewById in Kotlin”

Now lets have a look at the code , the layout contains a button( btn_change_text ) and a TextView (tv_hello). The button will be used to change the text of the TextView .

And in the activity lets add the import statement .
import kotlinx.android.synthetic.main.activity_main.*

Now our activity have some extention properties corresponding to the views of our layout i.e tv_hello of type TextView and btn_change_text of type Button. Lets add an onClickListener to the btn_change_text to change the text of tv_hello .

And to all the above code work we must enable the kotlin-android-extensions plugin in our app level build.gradle as discussed in step 1. Thus our build file look like the one below :

Leave a Reply

Your email address will not be published. Required fields are marked *