Monday, January 28, 2019

android kotlin - DataBinding example

MainActivity.kt

package com.cfsuman.jetpack

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.databinding.DataBindingUtil
import com.cfsuman.jetpack.databinding.ActivityMainBinding


class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // Inflate view and obtain an instance of the binding class
        // ActivityMainBinding came from activity_main.xml file name with Binding suffix
        // Make your data type as this format
        val binding:ActivityMainBinding = DataBindingUtil.setContentView(
            this, R.layout.activity_main) as ActivityMainBinding

        // Define the student to data bind in xml layout
        binding.studentClass = Student("Jenny Jones",25)
    }
}

// Make a student data class
// Class name should start with capital letter otherwise may cause an error
data class Student(val name:String, val age:Int)
activity_main.xml

<?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">
    <data>
        <variable
                name="studentClass"
                type="com.cfsuman.jetpack.Student"/>
    </data>
    <androidx.constraintlayout.widget.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/rootLayout"
            tools:context=".MainActivity"
            android:background="#fdfdfc">
        <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:id="@+id/textView"
                android:text="@{studentClass.name +'\n'+ studentClass.age}"
                android:layout_marginEnd="8dp"
                app:layout_constraintEnd_toEndOf="parent"
                android:layout_marginStart="8dp"
                app:layout_constraintStart_toStartOf="parent"
                tools:text="Sample Name"
                android:layout_marginTop="8dp"
                app:layout_constraintTop_toTopOf="parent"
                android:textSize="50sp"
                android:textColor="#03A9F4"
                android:textAlignment="center"
                android:layout_marginBottom="8dp"
                app:layout_constraintBottom_toBottomOf="parent"/>
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>
gradle settings

android {
    dataBinding {
        enabled = true
    }
}
gradle.properties

# To enable the new data binding compiler
android.databinding.enableV2=true
More android examples