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.