使用 DataBinding 访问整数数组

access integer array using DataBinding

我正在尝试使用 DataBinding 为 Integer 数据创建 RecyclerView,我已经通过在 string.xml 中声明 string-array 来尝试使用 String 数据, 是从我参考的地方回答。

现在我正在尝试使用 integer-array 实现它,但无法从 xml.

访问它

这是我的 integer.xml

<integer-array name="hours">
    <item>1</item>
    <item>2</item>
    <item>3</item>
    <item>4</item>
    <item>5</item>
    <item>6</item>
    <item>7</item>
    <item>8</item>
    <item>9</item>
    <item>10</item>
    <item>11</item>
    <item>12</item>
</integer-array>

这是我的 xml 文件

<android.support.v7.widget.RecyclerView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        app:entries="@{@integerArray/hours}">

和我的自定义绑定适配器

@BindingAdapter("entries")
public static void entries(RecyclerView recyclerView, Integer[] array) {
    recyclerView.setAdapter(new SimpleArrayAdapter(array));
}

但它显示错误 line 1:0 token recognition error at: '@integerArray/'

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. hours is missing

document 本身找到解决方案,我犯了愚蠢的错误。它应该是 intArray 而不是 integerArray,而在 BindingAdapter 中它应该是 int[]

app:entries="@{@intArray/hours}"

适配器应该是

@BindingAdapter("entries")
public static void entries(RecyclerView recyclerView, int[] array) {
    recyclerView.setAdapter(new SimpleArrayAdapter(array));
}

感谢您的回答。在这里我想分享从 integer-array Drawable 资源绑定图像的类似解决方案。

我的 integer-array 资源 Drawable:

<resources>
    <integer-array name="platform_images">
        <item>@drawable/android</item>
        <item>@drawable/iphone</item>
        <item>@drawable/windows</item>
    </integer-array>

</resources>

我的BindingAdapter函数:

object DataBindingUtil {
    @BindingAdapter("imageIndex", "images")
    @JvmStatic
    fun setImageResource(imageView: ImageView, imageIndex: Int, images: TypedArray) {
        imageView.setImageResource(images.getResourceId(imageIndex, 0))
    }
}

我的ImageView:

<ImageView
    android:layout_width="40dp"
    android:layout_height="40dp"
    android:src="@drawable/android"
    app:imageIndex="@{2}"
    app:images="@{@typedArray/platform_images}" />