Ankit Tale
Ankit Tale

Reputation: 2004

Creatign a custom binding adapter for databinding

I am fetching a web service of a profile in which I am obtaining gender as 1- Male 2- Female and 3- Not Preferred(Referenced). The web service gives me the value of as 1, 2, 3.

And I am using 2-way data binding for setting up thing I had written a custom binding adapter that is throwing an error to me.

Here is Custom Binder Code

 @BindingAdapter({"android:gender"})
    public static String loadGender(Integer genderCode) {
        if (genderCode == 1) {
            return "Male";
        } else if (genderCode == 2) {
            return "Female";
        } else if (genderCode == 3) {
            return "Not Preferred";
        }
        return null;
    }

and from xml I am accepting android:gender=@{userProfile.xxxx}

But I am not getting converted value


FAILURE: Build failed with an exception.

BUILD FAILED in 1s 19 actionable tasks: 4 executed, 15 up-to-date


Can someone please let me know why I am wrong

Upvotes: 2

Views: 1546

Answers (1)

Wess
Wess

Reputation: 779

You can't return a value from a Binding Adapter, you should rather do what you want inside of the Binding Adapter. Your method should be:

    @BindingAdapter("android:gender")
    public static void loadGender(TextInputEditText textInputEditText, int genderCode) {
        String gender = null;
        if (genderCode == 1) {
            gender = "Male";
        } else if (genderCode == 2) {
            gender = "Female";
        } else if (genderCode == 3) {
            gender = "Not Preferred";
        }

        textInputEditText.setText(gender);
    }

Data Binding will automatically pass in the TextInputEditText where you used your android:gender attribute.

Also, you should use your attribute as follows:

android:gender="@{userProfile.xxxx}" (Note quotation marks around @{})

Suggested improvement: Because you are not overriding a native Android attribute (android:gender is not normally an attribute on views), I would recommend that you rather call your attribute "gender". Thus, you define your Binding Adapter with @BindingAdapter("gender") and reference your attribute in XML as app:gender="@{userProfile.xxxx}"

Upvotes: 1

Related Questions