问题
I have a hard time making @BindingAdapter
to work in my project.
@BindingAdapter("imageUrl")
public static void setImageUrl(ImageView imageView, String url) {
Log.d("TEST","URL: " + url);
}
Above code shows how it is implemented in my ViewModel. Nothing special.
<ImageView
android:id="@+id/image_holder"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:layout_below="@id/profile_container"
app:imageUrl="@{item.imageUrl}"
tools:src="@drawable/placeholder_image"/>
This does not work. namespace app is unbound. So what am i missing. I tried following https://medium.com/google-developers/android-data-binding-custom-setters-55a25a7aea47#.6ygaiwooh and see how they set bindingAdapter. But there is something i have missed
回答1:
I encountered the same problem, I missed to bind layout using:
DataBindingUtil.setContentView(activity, layoutResId);
回答2:
I suggest to use "bind" namespace for bindable attributes and use same names for adapter parameter and layout attribute.
Adapter:
@BindingAdapter("bind:imageUrl")
public static void setImageUrl(ImageView imageView, String imageUrl) {
Log.d("TEST","URL: " + imageUrl);
}
Layout:
<ImageView
android:id="@+id/image_holder"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scaleType="centerCrop"
android:layout_below="@id/profile_container"
bind:imageUrl="@{item.imageUrl}"
tools:src="@drawable/placeholder_image"/>
where namespace "app" was replaced to "bind". On your Layout root:
xmlns:bind="http://schemas.android.com/apk/res-auto"
回答3:
Remember to add the following line to your app's build.gradle
file:
apply plugin: 'kotlin-kapt'
and check @BindingAdapter syntax:
@BindingAdapter("visibleOnScreen")
fun View.setVisibility(isVisible: ObservableBoolean) {
if (isVisible.get())
this.visibility = View.VISIBLE
else
this.visibility = View.GONE
}
in view's xml:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:visibleOnScreen="@{viewModel.errorOccurred}" />
viewModel:
var errorOccurred = androidx.databinding.ObservableBoolean(false)
回答4:
Give it a try with
@BindingAdapter({"bind:imageUrl"})
回答5:
You are using app:imageUrl="@{item.imageUrl}"
in the xml, make sure you have a String called imageUrl
in your model.
You must pass the url link of the image and not the binderAdapter's name.
Syntax :
app:BinderAdapterName="@{item.imagelink}"
来源:https://stackoverflow.com/questions/41533341/binding-adapter-not-working-properly