Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Databinding an in-memory Bitmap to an ImageView

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?

like image 337
Mike Avatar asked Feb 09 '16 23:02

Mike


2 Answers

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.

like image 93
CommonsWare Avatar answered Nov 18 '22 21:11

CommonsWare


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);
}
like image 38
hansonchris Avatar answered Nov 18 '22 20:11

hansonchris