Working with Data Binding Android
source link: https://www.ravirupareliya.com/blog/working-with-databinding-android/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Home Android / DataBinding Working with Data Binding Android
Working with Data Binding Android
In I/O 2015 Google announced a data binding library for Android. With data binding, you create an ongoing link between an element in the user interface and a value. Data binding is the process that establishes a connection between the application UI and business logic.
As a developer we always try to do tasks with lesser code, findViewById and setText would be the things which will increase line of codes. Data binding eliminates needs of these methods.
DataBinding is a support library so you can use it with the version higher than Android 2.1. Now we will see step by step instruction for how to use DataBinding in real time.
Step 1 : Enable dataBinding in your module level gradle.
Step 2 : Create a POJO class called Person.
Step 3 : update your layout for DataBinding. To enable data binding for your layout, simply wrap your existing elements in a layout element. Declare a variable of your POJO class .
Here person will be variable name through which we can access its property and methods. In above code we have written android:text=”@{person.firstName}” which will bind firstName value to that TextView. Don’t forget to replace com.androidgig.databindingdemo.Person with you package name
Step 4 : Establish DataBinding with the use of Java code.
You have noticed in above code that we have mentioned ActivityMainBinding but we have not declared it anywhere or where is that class? Your answer is it’s auto generated class for DataBinding. Binding class will be generated based on your layout file name. For Example if your layout name is activity_login.xml , you Binding class name will be ActivityLoginBinding. Here is output of your first DataBinding program.
Update value with clickListener
We have seen how to bind value without declaring TextView object and without using setText() at runtime. Now we will see how to update those values on any Button/View click.
Step 1 : change your POJO class by extending BaseObservable. Update getter methods by using @Bindable annotation. You need to notify property for changing its value for that use notifyPropertyChanged in setter methods.
Here BR is auto generated class like R file.
Step 2 : Define button in xml file
Step 3 : Update click event and call setter method to update TextView.
In next posts we will see lot more about DataBinding, so keep visiting AndroidGig.
Download source code
Ravi Rupareliya
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK