Using a BindingAdapter with a String Array from Resources

I have an almost simple idea: I want to create an adapter for a counter with a data binding API and a 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}"/> 

The address here is a simple class that has a field called country , which is a string and will contain the string ISO-3166-2. To keep it simple, the values ​​will be "DE" or "US".

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 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 completed for task ': app: compileDebugJavaWithJavac'.
java.lang.RuntimeException: Data binding errors detected.
**** / data binding error **** msg: Identifiers must be user-defined types from an XML file. countries are not enough File: path / to // coc-above.xml
loc: 95: 31 - 95:39
**** \ data transfer error ****

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

Do you see what I'm doing wrong?

By the way, I'm not sure if the annotations associated with the array resources are correct? I can not limit it to a string array.

+5
source share
1 answer

you can get it by specifying stringArray instead of array . Here is what I did with recyclerView to get value from resources, and it works great, it can also help you.

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 could be app:data="@{@stringArray/countries}" or app:keys="@{@stringArray/iso_3166_2}" .

and in the binding method

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

send this one for more details.

+5
source

All Articles