Issue
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.
Solution
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.
Answered By - Ravi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.