Android Data Binding Library | RIP FindViewById
Hi, 2018 is here & now its time for Data Binding in android, for binds the layouts we were used to findViewById & third party libraries like Butterknife-Square, but now there is no need to use ButterKnife as ButterKnife also using a bit of reflection which is bad for performance, although its not going to be affected much as Colt McAnlis said every mili-seconds count so ;) Lets start :-D
What is DataBinding?
New data binding features allow you to create declarative layouts in order to minimize boilerplate code by binding your application logic into your layouts.
The Data Binding Library offers both flexibility and broad compatibility — it’s a support library, so you can use it with all Android platform versions back to Android 2.1 (API level 7+).
Set-Up:
To start with databinding we need to add a databinding attribute in build.gradle file.
Data Binding Layout Files:
Data-binding layout files are slightly different and start with a root tag of layout followed by a data element and a view root element. This view element is what your root would be in a non-binding layout file. A sample file looks like this:
Here the user variable within data describes a property that may be used within this layout.
Expressions within the layout are written in the attribute properties using the “@{}
" syntax.
Data Object:
now create a data object for User like this:
Binding Data:
now everything is set-up now we need to set the data using the DataBinding, by default a Binding class will be generated based on the name of the layout file, in my case the layout file name is activity_main.xml
You’re done! Run the application and you’ll see John Name in the UI.
Here’s the project github repo
Thanks for reading this article. Be sure to clap to recommend this article if you found it helpful. It means a lot to me.
If you need any help then Join me on Twitter, Linkedin, Github, and Subscribe to my Youtube Channel.