Table of Contents
Android Data binding is one of the hot topic among Android developers ever since its first launch in Mid 2015, helping to build the apps faster.
This Article explains about the same, Data binding Library concept and how to use it in android using Kotlin. Data Binding not only supports in eliminating boilerplate code but also helps in faster development times and faster execution times.
- It eliminates boilerplate code (like findViewById)
- It provides a stronger readability, it would be easy to learn about it.
- Provides support to separate UI logic and business logic.
Similar Links: How to Read a File using Kotlin
Let’s see how to implement data binding in our application.
Configuring Android Data Binding:
To enable the usage of data binding in your app, first edit your application’s build.gradle file and add the following code snippet.
Data Binding Layout File:
Generally, in default layout files we have ViewGroup(E.g:LinearLayout, RelativeLayout) as parent tag. But, in this case to support data binding techniques, we must have <layout> tag as root tag. For a MainActivity class, a activity_main.xml layout would be like this:
Actual view (here it is Constraint layout) is defined within layout tag to support data binding techniques.The layout tag is a tag which indicates build system that, this file should be processed for data binding. Any layout file is without that tag , will not support data binding.
Data Binding Activity:
After this, binding class will be auto generated based on the name of layout file by default.To associate it in your class, invoke setContentView() using DataBindingUtil like this:
That’s it, we are done. Run the project and check output.
References: Data Binding Library implementation