android – 使用BindingAdapter和资源中的字符串数组

前端之家收集整理的这篇文章主要介绍了android – 使用BindingAdapter和资源中的字符串数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个几乎简单的想法:我想为带有数据绑定API和BindingAdapter的微调器生成一个适配器.这是我想要使用的 XML
<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”.

这是我简化的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:

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

}

当我尝试编译代码时,我收到此错误

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}”

你看到我做错了吗?

顺便说一句,我不确定与数组资源相关的注释是否正确?我发现无法将其限制为字符串数组.

解决方法

你可以通过引用stringArray而不是数组来获得它.以下是我使用recyclerView从资源中获取价值的方法,它完美运行,它也可能对您有所帮助.

在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中

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

在你的情况下,它可以是app:data =“@ {@ stringArray / countries}”或app:keys =“@ {@ stringArray / iso_3166_2}”.

并在绑定方法

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

请参阅this了解更多信息.

原文链接:https://www.f2er.com/android/318008.html

猜你在找的Android相关文章