MainActivity.kt
package com.cfsuman.jetpack
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.TextView
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("Hasiba Yeasmin",20)
// Define the listener for binding
binding.listener = ClickHandler()
}
}
// 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)
// Class to handle view click
class ClickHandler {
fun onTextViewClick(view: View, student: Student) {
val tv = view as TextView
tv.setBackgroundColor(Color.YELLOW)
tv.setTextColor(Color.RED)
tv.text = student.name.toUpperCase() + "\n" + student.age
}
}
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"/>
<variable
name="listener"
type="com.cfsuman.jetpack.ClickHandler"/>
</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"
android:padding="16dp"
app:layout_constraintTop_toTopOf="parent"
android:textSize="40sp"
android:textAlignment="center"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
android:background="#F8D1D1"
android:onClick="@{view-> listener.onTextViewClick(view,studentClass)}"
/>
</androidx.constraintlayout.widget.ConstraintLayout>
</layout>
gradle settings
// Enable data binding
android {
dataBinding {
enabled = true
}
}
gradle.properties
# To enable the new data binding compiler
android.databinding.enableV2=true