I have a bitmap in-memory (downloaded from a server application via a proprietary TCP/IP protocol stack) which I want to bind to an ImageView. I am able to manually bind the image using setImageBitmap, however; if I use the databinding library to bind other controls, the image does not display. How can I use the databinding library to bind to a property that contains the Bitmap object?
Asked
Active
Viewed 8,668 times
2 Answers
38
You should be able to do that with a @BindingAdapter
, something like:
@BindingAdapter("bind:imageBitmap")
public static void loadImage(ImageView iv, Bitmap bitmap) {
iv.setImageBitmap(bitmap);
}
Then, in your layout, your ImageView
would have bind:imageBitmap="@{...}"
, where ...
would be a binding expression that returns your Bitmap
.

CommonsWare
- 986,068
- 189
- 2,389
- 2,491
-
I am trying to load imageView using picasso in an item inside recyclerView using databainding, apparently when I scroll the up and down the images load again even if they were loaded a minute again, https://github.com/pankajnimgade/Tutorial101/tree/master/app/src/main/java/data/binding/list/activities/three – Pankaj Nimgade May 11 '16 at 05:24
6
You can use android.databinding.adapters.ImageViewBindingAdapter
, which is included in the data binding library.
In your view model, or whatever is bound to your view, implement a method such as this:
@Bindable
public Drawable getDrawable() {
return new BitmapDrawable(context.getResources(), bitmap);
}
And in your ImageView
, add something like this:
android:src="@{viewModel.drawable}"
Obviously, the viewModel
variable must have been declared in your layout.
This works because ImageViewBindingAdapter
has this method:
@BindingAdapter("android:src")
public static void setImageDrawable(ImageView view, Drawable drawable) {
view.setImageDrawable(drawable);
}

hansonchris
- 211
- 4
- 5