Data Binding in Android: Getting Started
In this Android Data Binding tutorial, you’ll learn how to link UI components to data in your app using a declarative format. By Evana Margain Puig.
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Sign up/Sign in
With a free Kodeco account you can download source code, track your progress, bookmark, personalise your learner profile and more!
Create accountAlready a member of Kodeco? Sign in
Contents
Data Binding in Android: Getting Started
20 mins
- Getting Started
- Why Use Data Binding
- How Data Binding Works
- Configuring for Data Binding
- Transforming a Standard XML Layout Into a Data Binding Layout
- Cleaning Up The Errors
- Autogenerated Binding classes
- Enabling Data Binding in Activities, Fragments and Related Code
- Adding Data Binding to Activities
- Binding the View
- Accessing The View Children
- Getting Rid of Errors
- Adding Data Binding to Adapters
- Value Binding
- Layout Variables
- Layout Expressions
- Binding Values in Activities
- Binding Values in Adapters
- Where to Go From Here?
Linking code files with user interfaces is one of the most common tasks an Android developer faces. As simple as it sounds, this process causes many runtime errors and consumes a lot of time. Wouldn’t it be great if there was a library that took care of that?
The Data Binding Library is here to the rescue! Android introduced this library as part of the Jetpack suite of libraries at Google I/O 2018.
Data binding lets you handle the communication between views and data sources reliably and simply. Following this pattern is critical for many important architectures in Android development, particularly MVVM, currently one of the most used Android architectures.
In this tutorial, you’ll build GoBuy, a shopping list app, to learn how to integrate the Data Binding Library into existing Android projects. Along the way, you’ll learn:
- How to enable data binding in your project
- How to convert an existing layout file to one that works with data binding
- How to work with code generated by the Data Binding Library in your Activities and Fragments
- How to use data binding in RecyclerView and ViewHolder
Getting Started
Download the starter project by clicking the Download Materials button at the top or bottom of the tutorial and unzip it. Extract both begin and end folders from the zip file. Open the begin project by selecting Import project (Gradle, Eclipse ADT, etc) from the welcome screen of Android Studio 3.5 or later.
Wait for the Gradle sync to finish. Look at the project structure.
As you can see in the screenshot above, the folder structure follows the MVVM architecture. There’s a file for the Model, another for the View and one for the ViewModel. During this tutorial, you’ll work with the files in the View folder, as well as the layout XML files in resources/layout, as shown in the screenshot below.
Build and run. You’ll see the initial version of your shopping list.
The app is functional and easy to navigate. Try adding a product by clicking the Add item button at the top-left corner of the screen. Fill in the dialog that appears and click the Save button. The item appears in the list with an option to edit or delete it.
Say you want to make sandwiches for your friends. You need to buy one loaf of bread, one jar of jam, two packages of cheese and a jar of mayonnaise. Add these to your shopping list.
Did you get a result similar to the screenshot above? Try playing with different values until you feel comfortable navigating through the app.
Before you dive into the project, it’s important to learn a little more about data binding.
Why Use Data Binding
Every developer wants clean and understandable code, but creating it is easier said than done. People rush, releases come one after another, clients want results and before you know it, your code is a mess.
Knowing this, the Android team decided to make things easier by standardizing development. To that end, they launched the Jetpack libraries, which include the Data Binding Library. This library offers several advantages:
- Less code: By keeping code in activities and fragments small, it helps you write cleaner and more readable code.
- Fewer errors: The binding is checked at compile time.
-
Faster apps: Since the binding isn’t done in
onCreate
, your app runs faster. -
Safer connection between views and code: Because it doesn’t bind at runtime, it’s safer to get the UI components than
findViewById()
. -
Safer connection between views and action: Data binding is safer than relying on
onClick()
, which can crash if you didn’t implement the requested method. - Easier: Since it has less code and causes fewer errors, it’s easier to test and maintain.
Now that you understand the benefits, it’s time to discuss how data binding works.
How Data Binding Works
Data binding is about connecting views in the XML layout with data objects: In this case, Kotlin code. The Data Binding Library generates the classes needed for this process.
Layout XML files that use data binding are different because they start with a root layout
tag followed by a data
element and a view root
element. This view root element is what your root would be in a non-binding layout file.
Each layout file then has its own generated data binding class. The Jetpack library does the job for you. By default, the class name is the name of the layout file in Pascal case and with the word binding at the end.
For example, in this project, activity_grocery_list.xml has the binding class ActivityGroceryListBinding.
Data binding has three main uses:
- Showing data.
- Handling user events.
- Invoking actions on layout variables.
With that in mind, it’s time to prepare the project for data binding.
Configuring for Data Binding
First, you’ll configure the project for data binding. Open the build.gradle from the app directory. Locate the TODO
comment at the bottom of this file and add the following code there:
dataBinding {
enabled true
}
This tells Gradle that you want to build your project with the Data Binding Library.
Build and run. You’ll see the same screen you did in the beginning.
Next, you’ll convert an existing XML layout to work with data binding.
Transforming a Standard XML Layout Into a Data Binding Layout
To convert a regular XML layout file to data binding layout, you need to follow three simple steps:
- Wrap your layout with a
layout
tag. - Add layout variables (optional).
- Add layout expressions (optional).
You’ll repeat step one in each of the three XML layouts in the project. Start by opening activity_grocery_list.xml. You’ll find a TODO
at the top of this file.
<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>
</data>
You need to close this tag at the very bottom of the file. So, go to line 63, add a new line and close it with the following code:
</layout>
With this code added, this layout can use data binding. Otherwise, it would be a standard layout file and generate the automatic binding files.