Binding views with Kotlin Android Extensions

Once the experimental features are turned on, we can reference synthetic view bindings to access our views. This means that the Android Extensions plugin will generate view bindings for us. In MainActivity, we can add the following import to reference the Button defined in our activity_main.xml file:

import kotlinx.android.synthetic.main.activity_main.button

Once we've included the import, we can reference that view directly without any call to findViewById() or another variable declaration:

button.apply {
text = "Hello Kotlin"
gravity = Gravity.START
setTextColor(resources.getColor(R.color.colorAccent))
}

By default, the view will be named after the android:id attribute in the XML. In this case, our button had an ID of "@+id/button", so the binding generated was named button. However, if you want to use a different variable name, or have a conflict with another name, you can update the import statement and provide an alternative name using the following syntax:

import kotlinx.android.synthetic.main.activity_main.button as theButton

After updating the import, we can now reference our button with the name theButton:

theButton.apply {
text = "Hello Kotlin"
gravity = Gravity.START
setTextColor(resources.getColor(R.color.colorAccent))
}

The synthetic view bindings will handle caching when used with activities and fragments and can be made to work with custom views as well. You can also control the caching strategy depending on your requirements by updating the androidExtensions block in your Gradle file:

androidExtensions {
// HASH_MAP, SPARSE_ARRAY, NONE
defaultCacheImplementation = "HASH_MAP"
}

By using the Kotlin Android Extensions for your view references, you can avoid third-party libraries such as Butterknife or multiple findViewById() calls. Whether you should use these synthetic bindings—DataBinding, ViewBinding, or findViewById()—will largely depend on your project and preferences, and you should evaluate them on a project-by-project basis.