【问题标题】:How to use DataBindingUtil with an Android spinner?如何将 DataBindingUtil 与 Android 微调器一起使用?
【发布时间】:2015-10-07 15:24:28
【问题描述】:

我正在尝试使用新的 Android 数据绑定库并在尝试使用所选值填充微调器时遇到以下错误。

错误信息(在 Android Studio 中编译期间):

错误:任务 ':app:compileDebugJavaWithJavac' 执行失败。 java.lang.RuntimeException:发现数据绑定错误。 ****/ 数据绑定错误 ****msg:找不到参数类型为 java.lang.String 的属性“app:selection”的设置器。文件:/Users/ove/Code/AndroidStudio/Samples/Receipts/app/src/main/res/layout/dialogfragment_inputamount_db.xml loc:40:29 - 40:44 ****\数据绑定错误 ****

我的布局文件如下所示(不完整):

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

        <variable
            name="receipt"
            type="com.example.model.Receipt" />
    </data>
    </LinearLayout>
    <Spinner
        android:layout_width="wrap_content"
        android:id="@+id/currency"
        android:layout_height="wrap_content"
        android:spinnerMode="dropdown"
        android:entries="@array/currency_array"
        app:selection="@{receipt.currency}" />
    </LinearLayout>
</layout>

有没有人设法让数据绑定与微调器一起工作?

【问题讨论】:

    标签: java android


    【解决方案1】:

    创建一个类 BindingUtils 并粘贴 setSelection 方法

    public class BindingUtils
      {
           @BindingAdapter({"bind:selection"})
           public static void setSelection(Spinner spinner, int position)
           {
                spinner.setSelection(position);
           }
      }
    

    内部微调

    app:selection="@{receipt.currencyIdx}"
    

    这就是你所要做的。

    【讨论】:

    • 这适用于单向绑定,那么双向绑定呢?在微调器中选择一个项目会更新模型。
    【解决方案2】:

    AbsSpinner 继承的设置器Spinner:setSelection 具有int 参数-而不是String

    public void setSelection(int position)

    你应该传递一个位置,而不是选择的值

    <Spinner
        android:layout_width="wrap_content"
        android:id="@+id/currency"
        android:layout_height="wrap_content"
        android:spinnerMode="dropdown"
        android:entries="@array/currency_array"
        app:selection="@{receipt.currencyIdx}" />
    </LinearLayout>
    

    【讨论】:

    • 如何将动态字符串数组传递给条目属性,即从服务器获取数据并放入数组字符串,然后要在微调器上填充它。那么我们如何使用数据绑定来做到这一点呢?
    猜你喜欢
    • 2018-11-18
    • 1970-01-01
    • 1970-01-01
    • 2021-02-26
    • 2022-01-14
    • 2018-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多