Age Calculator App – Data Binding

Screenshot showing a Kotlin Data class

This carries on from the previous post of View Binding. So set up gradle in the same way as described there, if you have not already. And then lets get started.

Create a new class of type data, with data that goes on a single View.

data class Age(
    var birthDate : String,
    var birthMonth : String,
    var birthYear : String,
    var birthday : Date,
    var ageDesc: String = "Teenager"
)

At the top of your XML layout file, within the <layout> block, but before any layout, add your data class binding block. The name is for linking to the individual fields The type is the fully qualified path to the data class you made above. This binds to the data class.

<data>
    <variable name="Age"
              type="com.sners.agecalculator.Age"/>
</data>

<androidx.constraintlayout.widget.ConstraintLayout etc...

Now within each field that is related, add the binding from the XML field to the XML data object. Use the android:text field. And link it to “{@=XMLobjectName.DataClassFieldName}”. eg

<EditText
       ...
        android:hint="@string/year_number"
        android:text="@={Age.birthYear}"
        .../>

In your activity, you need the same binding object from View Binding.

Make a private variable for your data class:

/**
 * @property age Age object
 */
private val age : Age = Age()




binding.age!!.agedesc= getString(R.string.agedesc)

In onCreate, bind the age variable to the binding:

binding.age = age

Again this is not difficult at all. But a word of warning. Anything set in onCreate() will sort itself out. But changes elsewhere will not appear to work until you add:

binding.invalidateAll()

Seems a bit of a brute force way of pushing changes, but will settle for something that works at this stage.

Leave a Reply

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