1 Answer

0 votes

Every Android developer knows well the findViewById() function. It is, without a doubt, a source of potential bugs and nasty code which is hard to read and support. While there are several libraries available that provide solutions to this problem, being libraries dependent on runtime, they require annotating fields for each View.

The Kotlin Android Extensions plugin allows us to obtain the same experience we have with some of these libraries, without having to add any extra code or shipping any additional runtime.

textView is an extension property for Activity, and it has the same type as declared in activity_main.xml.

Using Kotlin Android Extensions

Configuring the dependency

In this tutorial we're going to be using Gradle but the same can be accomplished using either IntelliJ IDEA project structure or Maven. For details on setting up Gradle to work with Kotlin, see Using Gradle.

Android Extensions is a part of the Kotlin IDEA plugin. You do not need to install additional plugins.

All you need is to enable the Android Extensions Gradle plugin in your project-local build.gradle file:

apply plugin: 'kotlin-android-extensions'

Importing synthetic properties

It is convenient to import all widget properties for a specific layout in one go:

import kotlinx.android.synthetic.main.<layout>.*

Thus if the layout filename is activity_main.xml, we'd import kotlinx.android.synthetic.main.activity_main.*.

If we want to call the synthetic properties on View (useful in adapter classes), we should also import kotlinx.android.synthetic.main.activity_main.view.*.

Once we do that, we can then invoke the corresponding extensions, which are properties named after the views in the XML file. For example, for this view:

a hidden caching function is generated inside MyActivity, so we can use the caching mechanism.

However in the following case:

fun Activity.b() {
this.textView.setText(“”)
}

We wouldn't know if this function would be invoked on only Activities from our sources or on plain Java Activities also. As such, we don’t use caching there, even if MyActivity instance from the previous example is the receiver.