Android BindingAdapter with StringRes and ObservableField<String>



我正面临一个复杂的数据绑定问题。

当我使用带有1个参数的自定义绑定适配器时,它工作得很好:

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

但是,只要我添加第二个参数(一个字符串res需要一个参数"%s属性"),编译失败…

@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"

你曾经遇到过这个问题吗?

谢谢!

我假设您的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,因此出现错误。如果你改变你的BindingAdapter的第二个参数来接受String而不是Int,它会工作得很好。

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

相关内容

最新更新