The Curious Website Designer

Setting Up Data Binding With Android Studio 3.5

Posted by The Curious Website Designer | Posted on Thu 29 Aug 2019

Setting Up Data Binding With Android Studio 3.5

Having just started exploring Android Studio 3.5, I was working through the basic tutorials and got stuck with getting Data Binding to work. The video tutorials, although great, frequently assume much more knowledge than I possess.

Having spent a full two days simply trying to understand what changes need to be made to the 'automatically' produced files to solve the problem, I have written this post as a reminder of the appropriate steps to take.

Changes to build.gradle (Module:app)

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'  //   < ======   add this entry
 
android {
. . .
    dataBinding {
        enabled = true
    }

 

 

at the bottom of the file add:

kapt { generateStubs = true }

 

Changes to activity_main.xml

1. Add <layout> tags around the whole file

 

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools">
    
    <data>
        <variable
            name = "usermodel"
            type = "com.example.databindingexample.viewmodel.User" />
    </data>
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity" >
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:text="@{usermodel.firstname}"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="30sp"
            android:textStyle="bold"
            />
    
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginTop="10dp"
            android:text="@{usermodel.lastname}"
            android:textColor="@color/colorPrimaryDark"
            android:textSize="30sp"
            android:textStyle="bold"
            />
    
    </LinearLayout>
</layout>

 

Reference: https://www.youtube.com/watch?v=xiRD0Vn0d-g