Next level of android development with data binding

Data binding in Android

No more programming to update UI and link events to the views

Photo by Goran Ivos on Unsplash
  1. Overview
  2. Integration
  3. Basics
  4. Data binding in Fragments, Dialogs and Recyclerview
  5. Two-Way binding
  6. Real-time useful features of data-binding
  7. Real-time challenges
  8. Useful links

Overview

Android team has been working continuously to provide developers with support libraries and API’s. Data-binding is one of the best libraries from the android team which makes developers life easy than ever.

The main purpose of data-binding is very simple, it acts as a bridge between layout and data-sources. To be more precise data-binding provides the view references in the logic part besides that it has numerous powerful features which you’ll be reading in the following part of this article.

With Data-binding library there is no need to write findViewbyId to link views with java/Kotlin files. Although there are third party libraries like butter-knife to do this work but using native support libraries has its own advantages.

Integration

Integrating data binding is one of the easiest things in android development. You need to add dataBinding block inside android block like below in build.gradle file and hit sync project.

android {
...
dataBinding {
enabled = true
}
}

Basics

Data-binding layouts are slightly different, they will start with a layout tag followed by data tag and then the normal layout. layout tag at the top-level will indicate the system this XML layout has data-binding properties.

The following code shows a sample layout file:

simple XML with data binding tags

user variable in the above code is a data class whose values can be used in the layout, that means we can bind data classes with layouts directly though there will be a few lines of code to write in our sources files. The following code shows User data class

Data class

Now you’re ready with the layout and model of the data that you want to show in layout, the only thing left is inflating the layout in Kotlin class. We don’t use setContentView anymore instead we use DataBindingUtil.setContentView.

Kotlin class with data binding

Through the data-binding object, we are accessing user variable that we mentioned in the layout and updating it with sample data, that’s all we do rest of the things will be taken care by Data-binding support library to update the UI.

This is a very basic level of implementing data-binding.

Data binding in Fragment, Dialog and Recyclerview

No matter in which component the data-binding layout is used the layout format will be the same as mentioned above.

We can implement data-binding in fragments, dialog and recyclerview adapter either by DataBindingUtil or using inflate method of layout binding. Have a look

data binding inflation in fragments

With the above code you can directly inflate data-binding layout into fragments and dialogs but coming to recyclerview it might be a little bit complicated. Let’s see an example of data-binding in recyclerview

Recyclerview with data binding

Here in recyclerview, we used DataBindingUtil to bind the view. I don’t know that you’ve observed or not that in onBindViewHolder we have removed all the boilerplate code and used setDivices method from XML to update the UI. The following code shows the XML layout of recyclerview item

Recyclerview item layout with data binding

Two Way Data-binding

What is two-way data-binding?

Until now what we did is, creating a layout with a variable tag in which we state the data class with the values to update the layout. But this won’t be the case all the time what if the values in variable class updated dynamically, how can it be updated in the layout? That’s where two-way data-binding comes into play, to understand two-way data-binding you should be familiar with the observable concept, I suggest you pause reading article and learn how observable work then continue reading the article.

Unlike normal data-binding, if any dynamic changes occur in the variables it will be reflected in the layout and vice-versa.

First, let’s have a look at the XML file that has two-way data-binding

Layout with two-way data binding

As you see the only difference is that we replaced ‘=@{Variable}’ instead of ‘@{Variable}’ and rest of the things will be done by data-binding.

Have look at data class

Data class to support two-way data binding

@Bindable in the model class and ‘=@{Variable}’ in the layout will take care of two way data-binding.

Real-time useful features of data-binding

View attributes with data-binding in XML

Until now you’ve seen how to update text using data-binding, along with that data-binding can be useful with any attributes in XML like visibility, text color, tint and many more have a look

Textview with some data binding tips

Image loading with data-binding

What good is data-binding if it doesn’t load remote images in the XML itself. Not only it has remote images loading in XML, but it also allow to use developer preferred library to load images like Glide, Picasso and so on.

We have to use BindingAdapters to implement this feature.

BindingAdapters : For every layout expression, there is a binding adapter that makes the framework calls required to set the corresponding properties or listeners. For example, the binding adapter can take care of calling the setText() method to set the text property or call the setOnClickListener() method to add a listener to the click event. The most common binding adapters, such as the adapters for the android:text property used in the examples in this page, are available for you to use in the android.databinding.adapters package.

We can also create custom binding adapter through which we achieve image loading. Let’s have a look at our custom binding adapter for image loading.

Binding adapter to load images

In the ImageBinder, there are two bindingAdapters one for local images which have resource id and other for remote images with urls. imageReourceId & imageUrl will act as attributes in layout. Let’s see how we use imagebinder in layout

how to use binding adapter to load images

TypeFace with data-binding

Are you one the developer who apply typeface like below, then this section is a lifesaver for you

tv_save.setTypeface(Font_Regular);

Here we use binding adapter to implement this just like image loading in the above section. Let me show you, FontBinder class

Binding adapter to apply typeface

Here we use two binding adapters one for textview and another for edittext. Let’s see how we can use this in the layout file

how to use typeface using binding adapters

Here we use font attribute from fontBinding class with the font file name to apply typeface to textview or edittext.

Click events with Data-binding

Until now we’ve seen how to set & get data between views and data classes, now it’s time to bind events.

Let’s consider a simple presenter class that contains methods which should be invoked on view clicks.

let’s see how to use this in layout

Real-time challenges

Impossible to understand data-binding errors

Data binding save developers from writing boilerplate code over and over again but it has its disadvantages, sometimes it comes up with weird errors that you don’t understand what you did wrong

For example, I’ve encountered the following error because I’ve used two-way binding with ImageBinder class shown above, turns out that will only work in normal binding. How the hell am I supposed to understand that from below error.

An exception occurred: android.databinding.tool.util.LoggedErrorException: Found data binding errors.

Bottom line there won’t be any clearer in the error caused by data binding most of the time(at least I don’t get it all the time). You’ve to figure out what’s wrong by reverse-engineering the code.

Cannot resolve data-binding

In my experience, this is one of the common error I have encountered. Sometimes when you open the project and head to a class with data binding it’ll show error cannot resolve layout-binding. You can run the app, rebuild the project or do whatever you want it will build successfully but the error won’t fade away sometimes.

Rebuild Problem

Sometimes when you create a new layout and try to access its data-binding reference from one of the source class it’ll show cannot resolve the error. If you’re lucky you can get the reference from rebuilding the project. If you still didn’t get the reference you’ve to restart android studio.

Useful Links

You can find me on Medium, Twitter and LinkedIn Cheers!

Thank you for reading.

Learn. Code. Write. Repeat. Visit me at https://about.me/sivaganesh_kantamani & Join my email list at https://sgkantamani.substack.com/p/subscribe

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store