androidandroid-databindingtwo-way-bindingandroid-binding-adapter

Android Two-way data binding data converter not working


Following https://developer.android.com/topic/libraries/data-binding/two-way#converters,
I am trying to implement a data converter for two-way data binding in android.

The functionality of the converter:
Given a 10 digit phone number, add country code to the phone number.

XML code:

<data>
    <import type="<package_name>.PhoneNumberStringConverter" />
    <variable
        name="model"
        type="<package_name>.MyViewModel" />
</data>

<androidx.appcompat.widget.AppCompatEditText
    android:text="@={PhoneNumberStringConverter.addExtension(model.storeDetailsEntity.storePhoneNumber)}"
    ... // Other irrelevant attributes are not shown
/>

Converter:

object PhoneNumberStringConverter {

    @InverseMethod("addExtension")
    @JvmStatic
    fun removeExtension(view: EditText, oldValue: String, value: String): String {
        return value.substring(3)
    }

    @JvmStatic
    fun addExtension(view: EditText, oldValue: String, value: String): String {
        return "+91$value"
    }
}

When I add the converter in the XML, the build is failing. Getting MyLayoutBindingImpl not found. Binding class generation issues.

Note:
1. Two-way data binding is working as expected, the issue is only with the converter.

Already referred:
Two-way data binding Converter

Edit:

Thanks to @Hasif Seyd's solution.

Working code:

PhoneNumberStringConverter:

object PhoneNumberStringConverter {

    @JvmStatic
    fun addExtension(value: String): String {
        return "+91$value"
    }

    @InverseMethod("addExtension")
    @JvmStatic
    fun removeExtension(value: String): String {
        return if (value.length > 3) {
            value.substring(3)
        } else ""
    }
}

XML:

android:text="@={PhoneNumberStringConverter.removeExtension(model.storeDetailsEntity.storePhoneNumber)}"

Changed addExtension to removeExtension.


Solution

  • There are some issues in the code. Since you are using two way binding convertors, first issue is you are trying to directly call the inverse binding adapter in the xml , but as per wat i see in ur convertor definition , binding adapter is removeExtension, so u have to assign that in the xml directly.

    Another possible reason could be because of having parameters view and oldValue , which are not required , if you remove those two parameters from the Binding Functions , your code would compile successfully