In this tutorial we’ll look into some other tricky usages of Data Binding in our application. For a better understanding of this tutorial, do view the Android Data Binding Tutorial.

Android Data Binding Recap

In the previous tutorial we looked into how Data Binding approach removes the need of using findViewById to hookup the UI view objects in our app code.
Another advantage of Data Binding over findViewById is that it enhances the performance of the application.
Using findViewById requires us to lookup the view in the entire hierarchy every time it’s invoked. Thus it requires a single pass through the entire view hierarchy for every child view. On the other hand, Data Binding uses just one single pass and stores all the field names of every child view layout. There’s no need for a second pass since we’ve already found all the views in the first pass itself.

Android Data Binding Overview

Data Binding has lots more to do than just getting rid of findViewById. You must have experienced scenarios where a ListView or a RecyclerView or just a normal layout for the sake uses a data model to add the relevant information into the layout. Even if we get the field names of the view layouts in our MainActivity it still requires us to write a lot of repetitive code snippets. Let’s say we have a layout where we’re adding data from a class dynamically and updating the values after a specific interval. The following code snippet shows an example implementation of Data Binding when the data is supplied to the layout from a Data Model class.


The class is given below.

The is given below.

We’ve used a timer that keeps changing the layout data alternately after every 3 seconds.
As you can see there is too much repetitive code for setText and setImageResource.
DataBinding allows us to directly assign the data from the DataModel class inside our xml layout. We’ll see how.

Android Data Binding Project Structure


Android Data Binding Code

We define the DataModel class variable object in the xml as shown in the layout below.


DataBinding has its own expression language for layout files. It allows us to assign the data directly in the xml attributes.

The is given below.

Doesn’t it look a lot cleaner and more readable now!

Few inferences drawn from the above code:

Android Data Binding App Output

The output of the application in action is given below.
android data binding advanced concepts

The expression language provided by DataBinding has much more to use than just specifying the data.
We can specify the xml attributes based on certain conditions as shown below.

The above line can be be written in a more compact form:

This brings an end to this tutorial. You can download the Android AdvanceDataBinding Project from the below link.

By admin

Leave a Reply

%d bloggers like this: