Data Binding – BindingAdapter

In this chapter of the Data Binding tutorial, we are going to extend our project with custum attributes. It means, we are going to create a BindingAdapter, then we gonna define some new attributes and actions for them.

In the previous chapter (Data Binding – Basics), we have talked about what is Data Binding, and where we can position it inside of the MVVM design pattern. We have created a very simple basic project, where we can print out our name in a TextView using a LiveData from a ViewModel.

GitHub

If you haven’t done the previous chapters, then from GitHub you can download the starter project for this chapter.

GitHub – DataBindingBasicsDemo

Binding adapters

Binding adapters are responsible for making the appropriate framework calls to set values. For example

      • setting a property value like calling the setText() method.
      • setting an event listener like calling the setOnClickListener() method.

The Data Binding Library allows us to specify the method called to set a value, provide our own binding logic, and specify the type of the returned object by using adapters.

Some attributes need custom binding logic. For example, there is no associated method for setting the color of the ProgressBar by its value. A static binding adapter method with the @BindingAdapter annotation allows us to customize how a setter method for an attribute is called.

Step 1 – Create the BindingAdpter class

Our first step will be the creation of the BindingAdapter Kotlin file. Inside of this file we are going to create our own attributes.

So, from the left Project tab and in Android view, expand the app option, then the java folder. Inside of the java folder click with the right mouse button on the package.

Then select New form the quick menu and from the submenu the Kotlin file/class option. In the popup window name the class as “BindingAdapter” and press Enter.

Step 2 – Create new binding method

After the creation of the BindingAdapter file, we can start to define our first binding method. This method will be very simple to show you how does binding adapters works in practice.

So, copy and paste the below method into the BindingAdapter file.


getLikes()

Note the first line, which is the annotation of the method. You should use the @BindingAdpater annotation to have your own attribute created. Then, in the parentheses, we can specify the name of the attribute. To distinguish it from the other attributes of the TextView, we gonna use the app word.

Next, check out the parameters, which are important in this case. The first parameter determines the type of the view that is associated with the attribute. The second parameter determines the type accepted in the binding expression for the given attribute.

Step 3 – Usage of the custom attribute

After the creation of the custom attribute, we can start using it in the XML layout.

So, open the activity_main.xml file from the res->layout folders and go to the tv_likes TextView. Then, add the next line to it.

app:getLikes=“@{likesViewModel.yourLikes}”

As you can see, we can use the attibute in the same way like the original attributes of the TextView. Then, we can pass the LiveData from the ViewModel as a parameter using the @{expression} format.

Step 4 – Handle click listener

Before we can run the app, we have to add the click listener for the btn_like Button. This button will call the increaseLikes() method from the LikesViewModel class, which then will increase the likes and set the value of the yourLikes LiveData.

So, add the next line to the btn_like Button.

android:onClick=“@{() -> likesViewModel.increaseLikes()}”

The former onClick attribute used an unsafe mechanism in which the increaseLikes() method in the activity or fragment is called when the view is clicked. If a method with that exact signature doesn’t exist, the app crashes.

The new way is much safer because it is checked at compile time and uses a lambda expression to call the increaseLikes() method of the view model.

Run the app

First in this chapter, run the app. After the successful build and run, the “0 likes” text should be printed out in the tv_likes TextView. When you click on the Like Button, then the likes gonna be increased.

Step 5 – Multiple Parameters

In some cases only one input data is not enough to run a function and we have to passat least one more argument. In case of the BindingAdapter, we also have this option.

Extend the annotation

So, open the BindingAdapter.kt file. There we have the getLikes() method with the @BindingAdapter annotation. Add one more value there, which is “app:context”. After thet it should look like below:

@BindingAdapter(“app:getLikes”, “app:context”)

This means in the XML file, that we can use this value also in the same way like we did in case of the “app:getLikes”. So, it will be a new attribute for the TextView either.

But why do we need the context? The best practice is to avoid the hard coded values. In our case it is the “likes” word, which should be placed in the strings.xml file.

Extend the strings.xml file

So, open the strings.xml file from the res->values folders and add there the below line:

<string name=“likes”>likes</string>

Extend the getLikes() method

Now, go back to the BindingAdapter.kt and change the body of the getLikes() method as you can see below.


getLikes()
Use the new attribute

Next step is to start using the newly created attribute. For this, open the activity_main.xml file and there add the below line to the tv_likes TextView.

app:context=“@{context}”

Note the value of the attribute, what we are passing. Basically the context value is available inside of the XML file either, and it means in our case the MainActivity::class.

Run the app

Run again the app and voila, the text has been extended by the word of “likes”.

Practice

In the second part of this chapter, we won’t describe in detailes the source code, because it will be the practice of the above mentioned knowledge.

Set scalable progress

We are going to set the scale of the ProgressBar. It means in our case, that we will set the maximum and the current values.

Frist, add the below code to the BindingAdapter.kt file.


setProgress()

Then, the next two line to the ProgressBar inside of the activity_main.xml file.

app:progress=“@{likesViewModel.yourLikes}”
android:context=“@{context}”

Run the app

If you run the app, and you click on the Like Button, then the value of the ProgressBar will change also.

Set color of the ProgressBar

The next practice is to change the color of the ProgressBar regarding its value.

The method goes into the BindingAdapter.kt file.


setProgressColor()

After the paste you will get some errors, because we haven’t added the colors to the colors.xml file. We gonna solve this now. So open the colors.xml file from the res->values folders and paste there the below lines.


New colors in the colors.xml

Finally add the below two lines to the activity_main.xml file.

app:progress=“@{likesViewModel.yourLikes}”
android:context=“@{context}”

Run the app

Run the app for the last time. If you start tapping the Like Button, then the color of the ProgressBar gonna be changed after every even number.

GitHub

The source code is available on GitHub

GitHub – add_binding_adapter branch

Questions

I hope the description was understandable and clear. But if you have still questions, then leave me comments below! 😉

Have a nice a day! 🙂

 


 

Follow and like us:
Click to rate this post!
[Total: 0 Average: 0]

Leave a Reply

Your email address will not be published. Required fields are marked *