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?
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
.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With