Introduction to Xamarin.Android With MVVMCross

Now-a-days, making cross-platform apps have become a global phenomena. Usually the path taken by most of the developers among us are made of HTML5/JavaScript and awesome HTML5/JavaScript is now at the point that some of us wonder if we have done everything with the language we know. Well, this article is for all the C# fanatics out there who hae a good time behind them on C# and want to give Android a shot without changing their language. Xamarin to the rescue. You'll get more on Xamarin from here. 
 
Xamarin and MvvmCross

As per Xamarin goes it has a couple of options to build cross-platform applications. That includes xamarin.ios, xamarin.android and xamarin.forms. Usually if you want a cross-platform app with a single UI code behind then xamarin.forms might be what you want. But today I'm going to use xamarin.android with a PCL behind. I usually tend to keep my UI apart for various platforms and thus this route feels really nice. And since I'm from Windows Phone, I love MVVM, I love how the code is separated from the views and I'd love something like that over xamarin.android so I can share my viewmodels over xamarin.ios and xamarin.android. MvvmCross to the rescue!
 
MvvmCross is a cross-platform MVVM library that allows you to put a common PCL directly from xamarin.android and xamrin.ios. And you get most of the Mvvm data binding to view sugars around this too. So, what are we waiting for? Let's check MvvmCross out! And, MvvmCross resides here.
 
Tools I've used here is mostly Xamarin Studio. You'd need a business subscription to build apps in Visual Studio. 
 
Installing Xamarin

Installing Xamarin is pretty straight forward. Anyone can download the installer from here and install it. If you have Visual Studio 2015 then probably you already have Xamarin templates installed. In any case it still works just fine with Visual Studio 2013.
 
Creating a PCL

Let's fire up our Xamarin studio and create a portable class library named NewsReader.cs. After you are done creating the project, delete the MyClass.cs file that has been created and right-click on the project name to go over the options. Move to the General section under build and you'll see the PCL profile you are using. I'm currently using the PCL profile 72 that targets .Net 4.5, Windows 8, Xamarin.Android and Xamarin.iOS.
 
 
 
Now, let's move on and install mvvmcross. To do that, all we need to do is right-click on the project name,  Add -> Add nuget packages and you can select over all the Nuget packages available for use. We will install the MvvmCross - Hot Tuna Started Pack. Make it sure that you are downloading the latest stable version. Im using 3.5.0 here. 
 
 
 
The moment you install the package, you will see some extra folders popping up and a C# class named App.cs popping up. Safely delete the ToDo-MvvmCross folder. You can definitely read what's inside, pretty gist of the entire tutorial here, but for our app purposes, that will not help.
Now, let's start peeking. Like every other mvvm library around MvvmCross has bestowed us with a ViewModels folder. If you go ahead and peek at it, you will see  a class named FirstViewModel has already being populated and it's inherited from MvxViewModel. That's the base class for viewmodels in MvvmCross. Pretty neat, huh?
 
Now, for today, we are just going to fetch some news from a RSS feed and show the titles over a list. Let's move on and create a folder named Services. After creating that folder let's create an interface named INewsLoadingService. And quite frankly it is dead simple.
  1. namespace NewsReader.Services  
  2. {  
  3.     public interface INewsLoadingService  
  4.     {  
  5.         Task<List<string>> LoadNews();  
  6.     }  
  7. }  
Now, we need to implement this very very very basic interface. Let's create a class under the Services folder and implement the INewsLoadingService.
  1. namespace NewsReader.Services  
  2. {  
  3.     public class NewsLoadingService:INewsLoadingService  
  4.     {  
  5.         public NewsLoadingService ()  
  6.         {  
  7.         }  
  8.  
  9.         #region INewsLoadingService implementation  
  10.   
  11.         public async System.Threading.Tasks.Task<System.Collections.Generic.List<string>> LoadNews ()  
  12.         {  
  13.             HttpClient client = new HttpClient ();  
  14.             var data = await client.GetStringAsync ("http://www.bbc.co.uk/sport/football/premier-league/rss.xml");  
  15.             var News = ParseResponse (data);  
  16.             return News;  
  17.         }  
  18.  
  19.         #endregion  
  20.   
  21.         private List<string> ParseResponse(string text)  
  22.         {  
  23.             var xml = XDocument.Parse(text);  
  24.             var items = xml.Descendants("item");  
  25.   
  26.             var list = items.Select(x => x.Element("description").Value.ToString()).ToList();  
  27.   
  28.             return list;  
  29.   
  30.         }  
  31.     }  
  32. }  
Now you can definitely see here that all I'm doing is fetching a set of news from a RSS feed and only getting their titles in a list of strings. Now, since our services are hooked up, let's move over to our FirstViewModel.cs and use this service. Our very simple ViewModel looks as in the following:
  1. namespace NewsReader.ViewModels  
  2. {  
  3.     public class FirstViewModel   
  4.         : MvxViewModel  
  5.     {  
  6.         private string _title = "NewsReader";  
  7.         public string Title  
  8.         {   
  9.             get { return _title; }  
  10.             set { _title = value; RaisePropertyChanged(() => Title); }  
  11.         }  
  12.   
  13.         private ObservableCollection<string> _newsCollection;  
  14.         public ObservableCollection<string> NewsCollection {  
  15.             get { return _newsCollection; }  
  16.             set { _newsCollection = value; RaisePropertyChanged (()=>NewsCollection);}  
  17.         }  
  18.   
  19.         public FirstViewModel ()  
  20.         {  
  21.             LoadData ();  
  22.   
  23.         }  
  24.   
  25.         public async void LoadData()  
  26.         {  
  27.             INewsLoadingService service = new NewsLoadingService ();  
  28.             NewsCollection=new ObservableCollection<string>(await service.LoadNews ());  
  29.   
  30.         }  
  31.     }  
  32. }  
Looks like we are all set with our very very very simple PCL. Now, let's add a new project to the solution. And it's going to be an Android project. Let's name it NewsReader.Android. 
 
 
 
Now, we do have our Android project that would be based on our PCL. Now go to the project references and add our NewsReader PCL to the project reference. 
 
 
 
Now, it's time to install MvvmCross in our Android project too. Kindly go to Nuget packages again and Install the MvvmCross - Hot Tuna Starter Pack into the Android project. We will definitely see some new stuff being populated there and  we will see a Views folder with a FirstView.cs there. There is a new XML file in the Resources/values folder too named MvxBindingAttributes.xml. This file helps MvvmCross to allow data binding in the layouts. Now, let's delete MainActivity.cs and Resources/layout/MainView.axml since we don't need these anymore. 
 
Now, as MVVM suggests, we need to hook up our viewmodel to our view and add the bindings. Before doing that let's go over our App.cs in the NewsReader project and have a peek. 
  1. namespace NewsReader  
  2. {  
  3.     public class App : Cirrious.MvvmCross.ViewModels.MvxApplication  
  4.     {  
  5.         public override void Initialize()  
  6.         {  
  7.             CreatableTypes()  
  8.                 .EndingWith("Service")  
  9.                 .AsInterfaces()  
  10.                 .RegisterAsLazySingleton();  
  11.                   
  12.             RegisterAppStart<ViewModels.FirstViewModel>();  
  13.         }  
  14.     }  
  15. }  
This definitely feels familiar. You can see the app starts with FirstViewModel so I really don't need to explicitly hook up the viewmodel for FirstView since FirstViewModel starts the app. Now, let's go over NewsReader.Android and in the Views folder, let's check out FirstView.cs.
  1. namespace NewsReader.Android.Views  
  2. {  
  3.     [Activity(Label = "View for FirstViewModel")]  
  4.     public class FirstView : MvxActivity  
  5.     {  
  6.         protected override void OnCreate(Bundle bundle)  
  7.         {  
  8.             base.OnCreate(bundle);  
  9.             SetContentView(Resource.Layout.FirstView);  
  10.         }  
  11.     }  
  12. }  
Now, you can definitely see the Activity annotation there and it also takes the activity label too. OnCreate is overridden with the FirstView.axml as the ContentView. So let's go over Resources/layout/FirstView.axml and see how to bind our FirstViewModel there. 
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  3.     xmlns:local="http://schemas.android.com/apk/res-auto"  
  4.     android:orientation="vertical"  
  5.     android:layout_width="fill_parent"  
  6.     android:layout_height="fill_parent">  
  7.   
  8.     <TextView  
  9.         android:layout_width="fill_parent"  
  10.         android:layout_height="wrap_content"  
  11.         android:textSize="40dp"  
  12.         local:MvxBind="Text Title" />  
  13.   
  14.    <MvxListView  
  15.         android:layout_width="fill_parent"  
  16.         android:layout_height="fill_parent"  
  17.         android:textSize="40dp"  
  18.         local:MvxBind="ItemsSource NewsCollection"  
  19.          />  
  20. </LinearLayout>  
Now, if you remember we had two properties exposed from our ViewModel. One were Title and the other were NewsCollection. For the title we used TextView, for all the XAMLites out there, TextView is just like TextBlock  in Windows Phone. And if you look closely we bound local:MvxBind to the property we wanted to bind from our ViewModel. Now you might ask how MvxBind works here, it looks definitely a bit different from the ones we had in XAML. Now if you look closely, the first binding statement is "Text Title". That means we are binding the android:text property of the TextView with the Title property that has been exposed from our ViewModel.
 
Now, let's come to the next part that starts with the component MvxListView, it's basically a MvvmCross implementation of Android's ListView and it allows you to bind your collection in the viewmodel in here. So, if you look down the binding on local:MvxBind you'll find we're binding ItemSource  as NewsCollection exposed from our viewmodel.
And that's it! Although it doesn't look so good, it's a start and seeing MVVM on Android is purely precious.
 
 
 
Pretty easy, huh? You can try the source code from Github here. And the zipped one is attached too.