Binding Adapter for Views

Updated 29 January 2020

Save

Hello Everyone, In this blog, we are about to learn about the binding adapter for a view as tittle said. So you are probably wondering what is the binding adapter is well you’ve probably been binding android: text to TextViews, android: checked to CheckBox and maybe even using the two-way data binding on the EditText, RadioButton,etc.. The built-in attributes are well covered and new tags were in order to bind to events. However, that doesn’t help with custom complex logic or in some cases Custom views. Also, how can you customize the setting logic?

What is Binding Adapter?

If you have used Android Data Binding for presenting data to views, chances are that you have defined some Binding Adapter annotated methods to convert data from your data model to view. it should be used when there is a more complex task to perform than usual, such as fetching an image from URL and setting it on the Image View or loading HTML content on the TextView that’s where you will need to use binding adapters. They can also be used when you need to update multiple attributes on a view at the same time.

Enough With theory Let’s do some coding

A usual Binding Adapter method is just a static method and performs data conversion and injection for the specific custom attribute in the layout file. For example:

Then we may have layout look like this:

You are probably wondering what is @JvmStatic well because Methods in Companion Object of Kotlin is not really static method, but methods of inner class Companion which is instantiated as a singleton within the outer class. Therefore is no real static method. So the DataBinding code generator cannot find it. But there is an easy fix for that, we may add an @JvmStatic annotation to those methods.

Android Data Binding does what you want most of the time without any code just call the setter on your View. When you want something more complicated, you can easily change it to your needs with binding adapters. Like loading the image from URL. That’s it for today from my side, but remember there are various other ways to use Custom Binding Adapter for views.

 

author
. . .

Leave a Comment

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


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home