#Xamarin : how to easily use the Picasso SDK and #MvvmCross to display efficiently images in your #Android Apps

, , Comments Off on #Xamarin : how to easily use the Picasso SDK and #MvvmCross to display efficiently images in your #Android Apps

Picasso is a great open-source SDK which let you display images efficiently on Android. I wanted to use it in my MvvmCross app because it really helps you having great display performances especially on list.

I have my images available as a remote HTTP URL in my ViewModel and I wanted to do this the easy and fast way. I then created a target binding !

MvvmCross lets you create your own target binding by following these steps :

  1. Create an new class which inherits from MvxAndroidTargetBinding.
  2. Register this binding using the name you want in your Setup class.
  3. Use this new binding target

Creating the target binding

You simply have to inherits from the asbstract class MvxAndroidTargetBinding and implements the SetValueImpl method which will set the value (provided as an arg) to the target element (provided as an arg too).

In our case, I use Picasso to the bitmap on an ImageView :
[csharp]
public class ImageUrlToLoadBinding : MvxAndroidTargetBinding
{
public ImageUrlToLoadBinding(View target) : base(target) { }

public int PlaceHolderToUse { get; set; }

protected override void SetValueImpl(object target, object value)
{
var imageView = (ImageView)target;
Picasso.With(imageView.Context)
.Load(value as string)
.Into(imageView);
}

public override Type TargetType => typeof(string);
}
[/csharp]

Registering the target binding

In your Setup class, you have to register this custom binding using the name you want. This name will be the one used as a Target in your MvxBind attributes. To do this, you have to override the FillTargetFactories method.

In our case, I use “PosterImageUrlToLoad” as a key :
[csharp]
protected override void FillTargetFactories
(IMvxTargetBindingFactoryRegistry registry)
{
// register custom binding here
registry.RegisterCustomBindingFactory<View>
("ImageUrlToLoad", v => new ImageUrlToLoadBinding(v));

base.FillTargetFactories(registry);
}
[/csharp]

Using the target binding

This is the easiest part because it’s a casual binding simpley using your “name” as a target. I removed all the other attributes in this example :
[xml]<ImageView
local:MvxBind="ImageUrlToLoad ImageUrlManager.FinalImageUrl"
/>[/xml]

Happy coding !