Android binding adapter passing multiple arguments cause error
我在
我正在尝试做一个接收多个参数的适配器。 这是我的代码:
XML格式
1 2 3 4 5 6 7 8 9 | <ImageView android:layout_width="@dimen/place_holder_size" android:layout_height="@dimen/place_holder_size" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:layout_centerVertical="true" app:url="@{image.imageUrl}" app:size="@{@dimen/place_holder_size}" /> |
绑定适配器类
1 2 3 4 5 6 7 8 9 10 11 12 | public class ViewBindingAdapters extends BaseObservable { @BindingAdapter({"bind:url","bind:size"}) public static void loadImage(ImageView imageView, String url, int size) { if (!Strings.isNullOrEmpty(url)) { Picasso.with(imageView.getContext()).load(url).resize(size, size).centerCrop().into(imageView); } } .... } |
但我收到此错误:
java.lang.RuntimeException: Found data binding errors.
****/ data binding error ****msg:Cannot find the setter for attribute 'app:url' with parameter type java.lang.String on android.widget.ImageView.
file:... li_image_item.xml
loc:30:27 - 30:40
****\\ data binding error ****
有人知道为什么吗?
提前致谢!
问题是
将您的
1 2 3 4 | @BindingAdapter({"bind:url","bind:size"}) public static void loadImage(ImageView imageView, String url, float size) { } |
你可以参考这个
我做错的是函数中参数的顺序。您可以在"绑定适配器"中添加多个属性,但是它们应该与方法中定义的顺序相同的参数匹配。
这是我的Kotlin代码片段
1 2 3 4 5 6 7 8 9 | @BindingAdapter(value = ["bind:brand","bind:model","bind:age"], requireAll = false) @JvmStatic fun bindProductDetails(linearLayout: LinearLayout, brand: String?, model: String?, age: String?) { if (brand != null && !brand.isEmpty()) { //code //code } } |
试试这个
1 2 3 4 5 6 | @BindingAdapter(value={"url","size"}, requireAll=false) public static void loadImage(ImageView imageView, String url, int size) { if (!Strings.isNullOrEmpty(url)) { Picasso.with(imageView.getContext()).load(url).resize(size, size).centerCrop().into(imageView); } } |
更新资料
您无需创建前缀
1 2 3 4 | @BindingAdapter({"url","size"}) public static void loadImage(ImageView imageView, String url, float size) { } |
在xml中使用任何前缀,例如
1 | app:url="@{image.imageUrl}" |
这是2020年,随着数据绑定库中的更改,您所需要做的就是用逗号分隔值声明它们。例
1 2 3 4 5 6 7 8 9 10 | @BindingAdapter("loadImageFrom","widthDp") fun loadImages(imageView: ImageView, url: String?, widthDp: Int) { url?.let { val height = (widthDp / 3) * 4 val fullUrl = getImagePosterUrl(url) Picasso.get().load(fullUrl).resize(widthDp.px, height.px).into(imageView) } } |
最重要的是要记住的是,您以DataBinding格式将数据提供给适配器属性。
在XML中提供Int作为参数的示例,您必须编写
1 | app:widthDp="@{120}" |
这是
app:your_attribute="@{your_data}"
P. S.-哦,还有件事,widthDp **。px **是一个扩展函数,它根据屏幕密度将dp值的