Data Binding vs Find Views by ID

Data Binding vs Find Views by ID

https://www.learn2crack.com/2016/06/android-data-binding-example.html (Image source)

During the SheCodeAfrica mentorship program, I saw the importance of data binding when combined with ViewModel and LiveData. It was Indeed a wonderful experience.

What is Data Binding?

Data Binding is the process of connecting the UI (User Interface) components of your android application to the data sources in your application using a declarative format rather than doing it programmatically. Data binding is carried out using the Data Binding support library which is a part of the Android Jetpack.

Why Data Binding?

When it comes to referencing views in android development, data binding is preferable to findViewsById() because of the following reasons:

  • Less boilerplate code: Data binding requires less code to reference a view because you only need to initialize one class called the Binding class, while the reverse is the case for findViewsById() because views have to be referenced with their IDs and declared as separate variables which can be very hectic especially when dealing with large codebases. Take a look at the code snippet for each of them:

Data Binding is to findViewById what Kotlin is to Java .

  • Speed: To find views in android development at runtime, the OS goes through the view hierarchy tree and searches for the view based on the ID that was used. This can greatly reduce the speed and performance of an application especially if it’s a large codebase that has a large number of views. Data Binding resolves this by creating a binding class at compile time which holds the views as objects for easy reference. Amazing!

Getting started with DataBinding

  • Enable dataBinding in the android section of your gradle(Module: app) file by setting ‘enabled’ to ‘true’ as shown below:

  • Wrap all tags in the XML layout in a tag as shown below:

  • Initialize the Binding class created during compile time and use it to reference the views:

Here, binding id used to reference the roll button.

Thanks for your time and I look forward to sharing my knowledge through articles, with you.

Did you find this article valuable?

Support Rita Okonkwo by becoming a sponsor. Any amount is appreciated!