【问题标题】:access integer array using DataBinding使用 DataBinding 访问整数数组
【发布时间】:2016-08-17 06:14:34
【问题描述】:

我正在尝试使用 DataBinding 为整数数据创建 RecyclerView,我已经尝试通过在 string.xml 中声明 string-array 来使用字符串数据,here 是我参考的答案。

现在我正在尝试使用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

【问题讨论】:

    标签: android data-binding android-databinding


    【解决方案1】:

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

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

    适配器应该是

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

    【讨论】:

      【解决方案2】:

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

      Drawable我的integer-array资源

      <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}" />
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-15
        • 2021-07-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多