I\'m trying to set drawable resource ID to android:src of ImageView using data binding
Here is my object:
public class Recipe implem
Answer as of Nov 10 2016
Splash's comment below has highlighted that it is not necessary to use a custom property type (like imageResource
), we can instead create multiple methods for android:src
like so:
public class DataBindingAdapters {
@BindingAdapter("android:src")
public static void setImageUri(ImageView view, String imageUri) {
if (imageUri == null) {
view.setImageURI(null);
} else {
view.setImageURI(Uri.parse(imageUri));
}
}
@BindingAdapter("android:src")
public static void setImageUri(ImageView view, Uri imageUri) {
view.setImageURI(imageUri);
}
@BindingAdapter("android:src")
public static void setImageDrawable(ImageView view, Drawable drawable) {
view.setImageDrawable(drawable);
}
@BindingAdapter("android:src")
public static void setImageResource(ImageView imageView, int resource){
imageView.setImageResource(resource);
}
}
Old Answer
You could always try to use an adapter:
public class DataBindingAdapters {
@BindingAdapter("imageResource")
public static void setImageResource(ImageView imageView, int resource){
imageView.setImageResource(resource);
}
}
You can then use the adapter in your xml like so
Be sure to notice that the name within the xml matches the BindingAdapter annotation (imageResource)
The DataBindingAdapters class doesn't need to be declared anywhere in particular, the DataBinding mechanics will find it no matter (i believe)