Introduction to DataBinding -2






In the last Blog we talked about, What is DataBinding and How to Implement it in our Android Project? If you don't know the answer to these 2 questions then I recommend you to have a look at Introduction to DataBinding , this is going to be a 5 min read.

Ok now, Let's move to the next step. In this blog we are going to set some data to our widgets(TextView), using DataBinding.

We will create a details screen of a student, we will show Student's name, age, standard, photo and blood group. So I have created a Student Class 

Our layout activity_main.xml will look like this :

If you notice in our xml, this does not look like a regular xml.


To use our Object class we create a variable of object class under <variable> tag.

android:text="@{student.name}"
If you see the [student.name], this works like name.setText(student.getName()). This is a nice and neat way of doing in DataBinding and it avoids memory leaks and null pointer  exception and runtime.

We are done here in our layout file. Let's move to our MainActivity Class.

Here we have created our layout using Databinding object. 

Using our databinding object, setting the clickListener at the button. Well, the is another way to do so in databinding but we will discuss this further.

So in our click function, we are creating a new Object of our Student Class and passing the value to the constructor and setting these object to our binding variable and DataBinding will take care of the rest.

Note: Here our setStudent() is the setter method of our variable that we have declared in our xml inside <variable> tag. If variable name changes then its setter method name will also change accordingly.
  
Finally let's talk about, how to get a set image using DataBinding in android. This works a little different than setText().

Here we are gonna use annotation processing or in our word we are gonna use databinding property and create our own custom attribute to set Image. 

If you see our Student Class,
 @BindingAdapter("android:loadImage"
public static void loadImage(ImageView view, int image){
view.setImageResource(image);
}


here we are passing the two argument the image and the view. Here the image is a student's image and the view is our imageview widget and use this as attribute in our <ImageView> xml.

That's it.....

In this discussion, we have learnt how to bind our object and set the values using DataBinding.

There is so much more in DataBinding and we will talk about that further till then 

Keep Learning,  Keep Coding... 😄😄!!

Comments