将BindingAdapter与资源中的字符串数组一起使用
我有一个几乎个简单的想法:我想使用数据绑定API和BindingAdapter为微调框生成适配器.这是我要使用的XML:
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}"/>
这里的地址是一个简单的类,它具有一个名为country
的字段,该字段是一个字符串,将包含一个ISO-3166-2字符串.为简单起见,值将为"DE"或"US".
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".
这是我的简化的 arrays.xml
:
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>
对于绑定,我编写了这个BindingAdapter:
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:
错误:任务':app:compileDebugJavaWithJavac'的执行失败.
java.lang.RuntimeException:发现数据绑定错误.
****/数据绑定错误**** msg:标识符必须具有XML文件中用户定义的类型.国家缺少它
文件:path/to/the/spinner-above.xml
loc:95:31-95:39
**** \数据绑定错误****
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 ****
我的xml的第95行是此行:app:value="@{address.country}"
Line 95 of my xml is this line: app:value="@{address.country}"
您看到我在做什么吗?
通过这种方式我不确定与数组资源相关的注释是否正确?我发现没有办法将其限制为字符串数组.
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.
您可以通过引用stringArray
而不是array
来获取它.这是我对recyclerView所做的工作,旨在从资源中获取价值,并且它运行良好,可能也对您有帮助.
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.
在string.xml中
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>
在layout.xml中
in layout.xml
app:entries="@{@stringArray/fi}"
在您的情况下可以为app:data="@{@stringArray/countries}"
或app:keys="@{@stringArray/iso_3166_2}"
.
in your case it can be app:data="@{@stringArray/countries}"
or app:keys="@{@stringArray/iso_3166_2}"
.
以及绑定方法
@BindingAdapter({"entries"})
public static void entries(RecyclerView recyclerView, String[] array) {
//get all values in array[] variable.
}
更多信息请参见此.