【问题标题】:Android BindingAdapter with StringRes and ObservableField<String>带有 StringRes 和 ObservableField<String> 的 Android BindingAdapter
【发布时间】:2021-08-10 16:39:34
【问题描述】:

我遇到了复杂数据绑定的问题。

当我使用带有 1 个参数的自定义绑定适配器时,它可以正常工作:

@BindingAdapter(value = ["myText"])
fun myBindingFun(
    view: View,
    myText: String?
) { ... }
myText="@{property.text}" <-- where text is an ObservableField<String>

但是,只要我添加第二个 args(需要 arg:"%s property" 的字符串 res),编译就会失败...

@BindingAdapter(value = ["myText", "resourceId"])
fun myBindingFun(
    view: View,
    myText: String?,
    @StringRes resourceId: Int,
) { ... }
Cannot find a setter for ... that accepts parameter type 'androidx.databinding.ObservableField<java.lang.String>'

If a binding adapter provides the setter, check that the adapter is annotated correctly and that the parameter type matches.

当我添加第二个参数时,我只需将 resourceId 属性添加到我的 XML 中:

myText="@{property.text}"
resourceId="@{@{string/my_string}}"

我也试过

myText="@{property.text}"
resourceId="@string/my_string"

你有没有遇到过这个问题?

谢谢!

【问题讨论】:

    标签: kotlin data-binding


    【解决方案1】:

    我假设你的 xml 布局文件中有这样的东西:

    <layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    
        <data>
    
            <variable
                name="property"
                type="..." />
        <data>
    
            <View
                android:layout_width="..."
                android:layout_height="..."
                myText="@{property.text}"
                resourceId="..."/>
    
    </layout>
    

    如果您想使用 BindingAdapter 传递 resourceId,则需要一些解决方法。将您的 xml 文件更新为:

        <data>
    
            <variable
                name="property"
                type="..." />
    
            <variable
                name="myStringResId"
                type="..." />
        <data>
            <View
                android:layout_width="..."
                android:layout_height="..."
                myText="@{property.text}"
                resourceId="@{myStringResId}"/>
    
    </layout>
    

    然后,在扩展绑定视图的地方,执行:

    binding.myStringResId = R.string.my_string
    

    据我所知,没有直接的方法可以将 (int) resourceId 传递给 xml。

    现在下面的阅读是可选的。假设你的 my_string 有这个值:

    <string name="my_string">I am awesome</string>
    

    如果是

    resourceId="@{@{string/my_string}}"
    

    您实际上是在传递值本身(在我们的例子中是I am awesome)——它的类型是String——作为BindingAdapter 的resourceId 参数,它需要Int,因此会出现错误。如果您将 Bi​​ndingAdapter 的第二个参数更改为接受 String 而不是 Int,它将正常工作。

    最后,resourceId="@string/my_string" 不是一个有效的注解。我知道这看起来合乎逻辑,不幸的是,您的代码将无法编译。

    【讨论】:

      猜你喜欢
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-29
      • 2019-03-06
      相关资源
      最近更新 更多