Skip to content

Instantly share code, notes, and snippets.

@ivacf
ivacf / profile_activity.xml
Created September 25, 2015 22:20
Android layout file that uses data binding to load a image into an ImageView
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" >
<data>
<variable
name="viewModel"
type="uk.ivanc.imagedatabinding.ProfileViewModel" />
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
@ivacf
ivacf / ProfileViewModel.java
Created September 25, 2015 22:16
View model that exposes a method using @BindingAdapter to load an image given a url
public class ProfileViewModel {
public String getImageUrl() {
// The URL will usually come from a model (i.e Profile)
return "http://cdn.meme.am/instances/60677654.jpg";
}
@BindingAdapter({"bind:imageUrl"})
public static void loadImage(ImageView view, String imageUrl) {
Picasso.with(view.getContext())
@ivacf
ivacf / ProfileActivity.java
Last active September 24, 2015 23:12
Activity that sets its content view using data binding and a view model
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ProfileActivityBinding binding =
DataBindingUtil.setContentView(this, R.layout.profile_activity);
binding.setViewModel(new ProfileViewModel(this));
}
@ivacf
ivacf / profile_activity.xml
Created September 24, 2015 23:08
Android layout that uses data binding to load a drawable into an ImageView
<layout xmlns:android="http://schemas.android.com/apk/res/android">
<data>
<variable
name="viewModel"
type="uk.ivanc.imagedatabinding.ProfileViewModel" />
</data>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
@ivacf
ivacf / ProfileViewModel.java
Last active April 22, 2018 19:07
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());