Age Calculator App – View Binding

Doing the Google Kotlin training courses on Udacity – here – they’re free, why wouldn’t you. If you use View Binding, you can link the view to the code at compile time – potentially improving the performance.

OK so the course is a few years old, and I’m getting some warnings – still a good course. Just cross reference for the latest details in the Kotlin language reference here: Using Kapt

Oh that is out of date as well – going down a rabbit hole – try here: Stack Overflow

Gradle:app

Which then takes me to here: Android Gradle Plugin

The first thing you need to do is update your app Gradle – the one that goes build.gradle(:app). You need to add the Kotlin Kapt plugin as follows:

plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id "org.jetbrains.kotlin.kapt" 
}

Or depending how your project is set up, you can alternatively do the following (same file)

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-kapt'

Enable data binding in the app gradle, at the top level.

android.buildFeatures.dataBinding true

Layout

Add a new top level closure to each layout resource. Move the namespace info into this tag.

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools">

    <androidx.constraintlayout.widget.ConstraintLayout ...

In the code

Make a binding variable. The type AgeCalcBinding is derived from the name of the layout file. In this case the layout file is called age_calc.xml.

/**
 * @property binding The binding class is autogenerated from the name of the layout it refers to
 */
private lateinit var binding: AgeCalcBinding

Instantiate it at the earliest opportunity:

super.onCreate(savedInstanceState)
binding = DataBindingUtil.setContentView(this, R.layout.age_calc)

Then you can remove all the findViewById variables, and instead access the fields directly with the binding. prefex.

binding.calculateButton.setOnClickListener {
    calculateAge()
}

binding.ageCalculated.setText(getString(R.string.fabulous))

And here’s how to do an adapter for an AutoCompleteTextView the binding way.

val monthNames = resources.getStringArray(R.array.months)
val adapter: ArrayAdapter<String> =
ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, monthNames)

binding.editMonth.threshold = 1
binding.editMonth.setAdapter(adapter)

Notes

It turns out to be very easy. Just be aware that you cannot just say binding.field.text = value for EditText. The reason is that EditText is an editable string type which you cannot assign. You have to use setText(value).

One thought on “Age Calculator App – View Binding

Leave a Reply

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