Data Binding Adapter: Write, Bind, Repeat

Julien Veneziano
Fueled Engineering
Published in
3 min readFeb 27, 2017

This article is a follow-up of my introduction to Data Binding.

Beyond simple view/data binding, the Data Binding framework also has the ability to create custom attributes (or setter) and bind them to actions.

1. Create a custom setter

You simply need to annotate a static method with the BindingAdapter annotation. This Annotation takes a string as a parameter. The string is the custom attribute, this static method will be bound to. Avoid to add the namespace in the annotation parameter as it will make the binding flaky. The first parameter of the method is the View object to apply the function to, and the second parameters is the value retrieved from layout XML.

Let’s tackle a common problem; Changing the color of a ProgressBar for pre-lollipop build:

  • Step 1: Create the binding method:
  • Step 2: Add the custom attribute to your view:

Notice the value for the custom parameter is in a data binding code block. If you don’t decorate the value in a data binding block, the value sent to the custom setter will be a String.

  • Step 3: Enjoy the reusability :P

2. Create a custom setter with multiple attribute

Additionally, you can create a custom setter that uses several custom attributes. Simply pass an array of custom attributes to the annotation and specify if all the attributes are required or not.

For example, let’s create a custom setter that loads an image remotely using Glide or Picasso with the full placeholder, error etc… support.

3. Create a custom setter with lambda expression support

Yes ladies and gentlemen, you can create a setter that support lambda expression. A little bit of work is required as you would need to declare an interface in order for the lambda expression to be converted in an anonymous class that implements it.

To illustrate this case, let’s implement a setter that will trigger any action when the keyboard “done” button is pressed.

Conclusion

Custom setters are a great way to reuse code design to configure views as well as remove that code from your Activities and Fragment.

--

--