【问题标题】:Cannot set string array for spinner using Android data binding无法使用 Android 数据绑定为微调器设置字符串数组
【发布时间】:2016-08-09 03:06:32
【问题描述】:

我现在有一个微调器,我想通过数据绑定功能将数据加载到微调器。我试图找到在 XML(https://developer.android.com/topic/libraries/data-binding/index.html#expression_language) 中声明字符串数组的方法,但没有找到满意的结果。

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:apps="http://schemas.android.com/apk/res-auto">

<data>
    <import type="android.util.SparseArray"/>
    <variable
        name="statuslist"
        type="SparseArray<String>"/>
</data>
...
<android.support.v7.widget.AppCompatSpinner
        android:id="@+id/spn_status"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignStart="@+id/spinner1"
        android:layout_below="@+id/btn2"
        android:entries="@{statuslist}"
        apps:adapter="@{statusAdapter}"/>
</layout>

构建时出现如下错误。

错误:任务 ':app:dataBindingProcessLayoutsDebug' 执行失败。

org.xml.sax.SAXParseException; systemId:文件:/C:/Users/../app/build/intermediates/res/merged/debug/layout/testdialog.xml;行号:24;列号:30;与元素类型“null”关联的属性“type”的值不能包含“

但是,有一些令人困惑的事情。

  1. 当我尝试使用网站上显示的 SparseArray 时。我在 Android Studio XML 编辑器中发现“无法解析 sysmbol”。
  2. 我不知道设置微调器的数组值是否正确,因为网站上没有微调器数据绑定的官方说明。

【问题讨论】:

  • 你是否在 build.gradle 中启用了数据绑定?
  • 是的,我在 build.gradle 中启用了数据绑定。这是我的Android Studio的信息(版本:2.1.2,JavaVersion:1.7)

标签: android android-spinner android-databinding


【解决方案1】:

你导入 SparseArray 了吗?

试试这个:

<data><import type="android.util.SparseArray"/></data>

【讨论】:

  • 我忘记在问题中添加此语句。我试过了,但它不起作用
  • SparseArray 改为 SparseArray ,再试一次
  • 这样试过了,还是不行。仍然显示“无法解析符号”错误
  • 我的意思是在 type 字段中只写 SparseArray 而不是 SparseArray
【解决方案2】:

这是使用资源的 array.xml

中的字符串数组设置微调器的一种非常简单的方法
<Spinner
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:entries="@array/spinner_array_items"/>

spinner_array_items 应包含可在微调器下拉列表中找到的项目列表。

【讨论】:

    【解决方案3】:

    SparseArray&amp;lt;String&amp;gt; 更改为SparseArray&amp;lt;String&amp;gt;

    【讨论】:

      【解决方案4】:

      我的实现逻辑是基于你的,但使用ArrayList 而不是SparseArray

      XML:

          <data>
              <import type="java.util.ArrayList" />
              <variable
                  name="cities"
                  type="ArrayList&lt;String>"
              />        
          </data>
      
          <!-- Location -->
          <Spinner
              android:id="@+id/dd_city"
              android:entries="@{cities}"
              style="@style/dropdown"
          />
      
      

      现在,我们只需要通过绑定类将ArrayList 绑定到cities 变量即可。

      至少数据会被绑定:)。

      TC。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-27
        • 2015-11-30
        • 1970-01-01
        • 2017-11-10
        相关资源
        最近更新 更多