Android binding adapter passing multiple arguments cause error

ID : 131396

viewed : 5

Tags : androidandroid-databindingandroid

Top 5 Answer for Android binding adapter passing multiple arguments cause error

vote vote

94

Problem is @dimen/place_holder_size, it returns float while you are catching it as int

change you BindingAdapter method to this

@BindingAdapter({"bind:url", "bind:size"}) public static void loadImage(ImageView imageView, String url, float size) {  } 

you can refer this

vote vote

85

What I did wrong is the order of the arguments in the function. You can add multiple attributes in Binding Adapter, but they should match the arguments with the same sequence defined in the method.

Here is my code snippet for Kotlin

@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      } } 
vote vote

70

try this

 @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);         }     } 
vote vote

63

Update

You don't need to create prefix bind:, just use this.

@BindingAdapter({"url", "size"}) public static void loadImage(ImageView imageView, String url, float size) {  } 

In xml use any prefix like app:

app:url="@{image.imageUrl}" 
vote vote

60

Apart from the example provided above by @Kishan Solanki, And with changes happening in the Data Binding library, all you need is to declare them with comma separated values. Example

@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)     }  } 

Bu the most important thing to remember is that you provide the data to the adapter attributes, in the DataBinding format.

example to provide Int as parameter in XML you have to write

app:widthDp="@{120}" 

which is

app:your_attribute="@{your_data}"

P. S. - Oh and one more thing, widthDp**.px** is an extension function which converts Int of a dp value to relevant pixels value based on screen density. So don't get confused.

Top 3 video Explaining Android binding adapter passing multiple arguments cause error

Related QUESTION?