Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a BindingAdapter with a string-array from the resources

I have an almost simple idea: I want to generate an Adapter for a spinner with the data binding API and an BindingAdapter. Here is the XML I want to use:

<Spinner
    android:id="@+id/country"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:value="@{address.country}"
    app:data="@{@array/countries}"
    app:keys="@{@array/iso_3166_2}"/>

Address here is a simple class which has a field called country which is a String and will contain a ISO-3166-2 String. To keep it simple the values will be "DE" or "US".

This here is my simplified arrays.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string-array name="iso_3166_2">
        <item>DE</item>
        <item>US</item>
    </string-array>

    <string-array name="countries">
        <item>@string/country_DE</item>
        <item>@string/country_US</item>
    </string-array>
</resources>

For the binding I wrote this BindingAdapter:

@BindingAdapter({"value", "data", "keys"})
public static void generateAdapter(Spinner spinner,
                                   String value,
                                   @ArrayRes int data,
                                   @ArrayRes int keys) {

}

When I try to compile the code I get this error:

Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
java.lang.RuntimeException: Found data binding errors.
****/ data binding error ****msg:Identifiers must have user defined types from the XML file. countries is missing it
file:path/to/the/spinner-above.xml
loc:95:31 - 95:39
****\ data binding error ****

Line 95 of my xml is this line: app:value="@{address.country}"

Do you see what I am doing wrong?

By the way I am not sure about the annotations related with the array resources is that correct? I find not way to limit it to a string array.

like image 830
rekire Avatar asked Apr 27 '16 20:04

rekire


1 Answers

you can get it by refering stringArray instead of array. Here is what i have done with recyclerView to get value from resources and it is working perfectly, it might help you also.

in string.xml

<string-array name="myItems">
    <item>Item 1</item>
    <item>Item 2</item>
    <item>Item 3</item>
    <item>Item 4</item>
    <item>Item 5</item>
    <item>Item 6</item>
</string-array>

in layout.xml

app:entries="@{@stringArray/fi}"

in your case it can be app:data="@{@stringArray/countries}" or app:keys="@{@stringArray/iso_3166_2}".

and in binding method

@BindingAdapter({"entries"})
public static void entries(RecyclerView recyclerView, String[] array) {
    //get all values in array[] variable.
}

refer this for more.

like image 70
Ravi Avatar answered Nov 16 '22 23:11

Ravi