DEV Community

Cover image for 2 Ways to Implement Binding Adapters
Vincent Tsen
Vincent Tsen

Posted on • Updated on • Originally published at vtsen.hashnode.dev

2 Ways to Implement Binding Adapters

One way is using function parameter and another way is using extension function.

There could be more than 2 ways to implement binding adapters, but this is what I know. Let's look at what binding adapters are first.

What is Binding Adapters?

Binding adapter is used for implementing custom attribute in your layout file. For example, instead of using the defaultandroid:text attribute, you want to customize it by creating a new attribute app:customText.

Default Attribute - android:text

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Hello World!"/>
Enter fullscreen mode Exit fullscreen mode

Custom Attribute - app:customText

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:customText="@{`Hello World!`}"/>
Enter fullscreen mode Exit fullscreen mode

To implement custom attribute, we use binding adapters. Binding adapter is part of the data binding library. So you need to enable data binding in your build.gradle module file.

android {
    ...
    buildFeatures {
        dataBinding true
    }
}
Enter fullscreen mode Exit fullscreen mode

To implement a binding adapter, you need to annotate the function with @BindingAdapter("attribute name here") together with View class that you want to bind to. It can be done by passing the View class (e.g. TextView) as a function parameter or using the extension function.

1. Pass View as Function Parameter

I am not sure if this is a standard way (or maybe a recommended way?) but this is in the official documentation. What I learned initially is the second method below (i.e. using the extension function)

@BindingAdapter("customText")
fun setCustomText(view:TextView, item: String) {
    view.text = "My Custom String: $item"
}
Enter fullscreen mode Exit fullscreen mode

2. Use View Extension Function

@BindingAdapter("customText")
fun TextView.setCustomText(item: String) {
    text = "My Custom String: $item"
}
Enter fullscreen mode Exit fullscreen mode

Because this is an extension function, you can call it in code directly like this.

binding.textView.setCustomText("Hello World!")
Enter fullscreen mode Exit fullscreen mode

You can do that with the first method too, but the second method is more readable.

Personally

I prefer the second method, use the extension function to implement binding adapter. It reflects the actual intention, which is to extend theTextView functionality.


Originally published at https://vtsen.hashnode.dev.

Latest comments (0)