Skip to content

Instantly share code, notes, and snippets.

@ivacf
Last active April 22, 2018 19:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivacf/8308d4d6cd4b4299fe5b to your computer and use it in GitHub Desktop.
Save ivacf/8308d4d6cd4b4299fe5b to your computer and use it in GitHub Desktop.
View model that downloads an image using Picasso and data binding
public class ProfileViewModel {
// The URL will usually come from a model (i.e Profile)
static final String IMAGE_URL = "http://cdn.meme.am/instances/60677654.jpg";
public ObservableField<Drawable> profileImage;
private BindableFieldTarget bindableFieldTarget;
public ProfileViewModel(Context context) {
profileImage = new ObservableField<>();
// Picasso keeps a weak reference to the target so it needs to be stored in a field
bindableFieldTarget = new BindableFieldTarget(profileImage, context.getResources());
Picasso.with(context)
.load(IMAGE_URL)
.placeholder(R.drawable.placeholder)
.into(bindableFieldTarget);
}
public class BindableFieldTarget implements Target {
private ObservableField<Drawable> observableField;
private Resources resources;
public BindableFieldTarget(ObservableField<Drawable> observableField, Resources resources) {
this.observableField = observableField;
this.resources = resources;
}
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
observableField.set(new BitmapDrawable(resources, bitmap));
}
@Override
public void onBitmapFailed(Drawable errorDrawable) {
observableField.set(errorDrawable);
}
@Override
public void onPrepareLoad(Drawable placeHolderDrawable) {
observableField.set(placeHolderDrawable);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment