How to setup Data Binding in Android Studio?

Viewed 3584

The Android Developers Guides for Data Binding has the following code to enable data binding in build.gradle file in app module:

android {
    ...
    buildFeatures {
        dataBinding true
    }
}

But after after adding this code the Build Fails with this error:

error: package androidx.databinding does not exist

Gradle Version : 4.0.1

Language : Kotlin

1 Answers

Set up with data binding:

inside Build.gradle(:app)

dataBinding {
        enabled = true
    }

Dependencies

implementation 'com.android.databinding:compiler:3.5.1'

Bind your data in xml like this:

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:app="http://schemas.android.com/apk/res-auto">
    
    <data>
        <variable
            name="item"
            type="DataModel" />
    </data>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        android:text="@{item.name}"/>// binding data from model

</androidx.constraintlayout.widget.ConstraintLayout>
</layout>

For more detail :here

Note: sync gradle and clean & rebuild project

Related