Data Binding in Android

The Green Dot
2 min readNov 22, 2020

--

What and why?

One way to manipulate things in a layout is to use fineViewById(R.id.xxx) to find elements at runtime and do stuff, which can be slow for complex layouts.

Another option is to connect layout to Activity or Fragment using Data Binding. (This gives performance enhancements)

Data binding is a pattern to solve the above-discussed problem by, connecting layout to activity/fragment at compile time.

The compiler creates a helper class when the activity/fragment is created called the binding Class.

How?

  1. Enable data binding in build.gradle.
android {
...
buildFeatures {
dataBinding true
}
}

2. wrap layout xml in a <layout> xml tag, that will contain the view groups & views.

3. Import the Binding class created by the compiler. The binding class’s name is derived from the name of the layout file.

activity_main.xml → ActivityMainBinding

4. Create a late init var binding in the Activity/fragment and initialize it using the binding class generated by the compiler. → This happens in onCreate() for activity

binding = DataBindingUtils.setContentView(this, R.layout.activity_main)

Data binding can not only be used to access view elements on activity/fragment but can also provide a data object to views (to be used directly in XML layout)

Create a data class, let layout know about the data class using <variable> then instantiate the object in the Activity/Fragment. (Again in onCreate() for activity)

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

The Green Dot
The Green Dot

Written by The Green Dot

0 Followers

Talks about Brain Health & Computer Science

No responses yet

Write a response