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
// Test the example by alternating the true false values
//binding.studentClass = Student("Hasiba Yeasmin",true)
binding.studentClass = Student("Hasiba Yeasmin",false)
}
}
// Make a student data class
// Class name should start with capital letter otherwise may cause an error
data class Student(val name:String, val isVisible:Boolean)
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"/>
<import type="android.view.View"/>
</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}"
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="#B30404"
android:textAlignment="center"
android:layout_marginBottom="8dp"
app:layout_constraintBottom_toBottomOf="parent"
android:visibility="@{studentClass.isVisible? View.VISIBLE : View.GONE}"
android:background="#F8D1D1"
/>
</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