Best use of Data binding (Android)

Ashutosh jha
2 min readApr 8, 2020

What is data binding?

According to the Android official documentation, the Data Binding Library is a support library that allows you to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically.

So basically, it is a tool through which we can easily bind your data with your UI component without writing too much of code. In the words of native android developer, you can bind data to the UI in your XML itself just by passing the data from your java/kotlin file.

Best practical uses of data binding in android

Multi-lingual app

If you are planning to develop a multiple language supporting app (e.g. a vernacular content delivery platform), i will suggest you to use data binding for switching one language to another, rather than to write logic for each language available in your application. This will give you a smooth experience while binding data with UI component.

Complex form UI

Imagine a form having multiple fields or multiple UI components, such as EditText, Radio Groups, TextView, Buttons etc, and you want to hide/show some fields according to the option selected by user, in that situation data binding can make it much easier. Now you don’t need to change visibility of UI component through java/kotlin file. You can simply make it using data binding. How?

  1. Create a configuration object and define field’s visibility here. Suppose we have three fields A, B and C. Now we want to hide B. For this create an object having three fields and set the value B as hidden in this object (Preferable type of these fields are Boolean).
  2. Pass this object to your XML using data binding and set the visibility of UI component according to the defined value of that fields in object you passed to XML. And it’s done.

Separate code maintenance

If you want to keep all the UI logic and the business logic separately, the data binding will help you to do so.

Developer’s opinion

Although data binding gives the leverage to minimize the writing of code, still most of the developers don’t really love it due to some sort of hassle it creates while writing code. Few are:

  1. You need to put an extra layout layer in your XML.
  2. You need to clean and rebuild your project whenever you modify parent of your XML.
  3. The syntax is bit complex to remember.
  4. This will sometime reflects unnecessary bugs in your code, which you can resolve by invalidating cache only.

If you like this article, do give it a thumbs up, comment on it and share with your friends. Suggestions and corrections are welcome.

--

--

Ashutosh jha

Techie from 🇮🇳 | Writing blogs on Android, Flutter, UI/UX and many more. Lead Engineer