How to use Android Data Binding in custom views?

Furkan Aşkın
ProAndroidDev
Published in
2 min readMay 23, 2021

--

As you know the Data Binding Library is a cool part of Android Jetpack library for reducing boilerplate code and allows you to connect views with data in a much more powerful way than was possible previously. In this article i’m going to explain how we can use data binding in our custom views.

Getting started

Most of the time we are creating custom views for better performance, customization etc. but if you using data binding in your projects and if you don’t using data binding in your custom views, it’s not cool. Probably, it’s looking something like that :

But if you want to use your custom view with data binding component actually you don’t need to handle this attributes.

Automatic Method Selection

When you define a attribute like this :

data binding library has automatic method selection ability, that means for an attribute named currencyCode, the library automatically tries to find the method setCurrencyCode(arg) that accepts compatible types as the argument. The namespace of the attribute isn't considered, only the attribute name and type are used when searching for a method. In the other hand if automatic method selection won’t work for your attribute name or you want to change your setter method for your attribute you can use Binding Methods.

Binding Methods

Binding Methods gives you ability to change your setter for your custom view’s attribute. You can put this methods above your class using @BindingMethods annotation or you can create an empty class with these annotation.

define a function named as whatever you want then just put these function with attribute in binding methods.

with this way you can set different setter names for your attribute.

Binding Adapters

If you have functions with multiple parameters in your custom view and you want to use these functions with data binding this time you should use binding adapters.

You can create a binding adapter like this for setting your paddings as in the example.

That’s all, thanks for reading! If you enjoyed this story, please click the 👏 button and share it to help others!

If you have any kind of feedback, feel free to connect with me on Twitter.

--

--