Introduction to Xamarin.Android With MVVMCross


Nowadays, making cross-platform apps have become a global phenomenon. Usually, the path taken by most of the developers among us is 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 have 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, 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 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 so I can share my viewmodels over xamarin.ios and MvvmCross to the rescue!
MvvmCross is a cross-platform MVVM library that allows you to put a common PCL directly from 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-clicks 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 an 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.         }    
    9.         #region INewsLoadingService implementation    
    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 ("");    
    15.             var News = ParseResponse (data);    
    16.             return News;    
    17.         }    
    19.         #endregion    
    21.         private List<string> ParseResponse(string text)    
    22.         {    
    23.             var xml = XDocument.Parse(text);    
    24.             var items = xml.Descendants("item");    
    26.             var list = items.Select(x => x.Element("description").Value.ToString()).ToList();    
    28.             return list;    
    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.         }    
      13.         private ObservableCollection<string> _newsCollection;    
      14.         public ObservableCollection<string> NewsCollection {    
      15.             get { return _newsCollection; }    
      16.             set { _newsCollection = value; RaisePropertyChanged (()=>NewsCollection);}    
      17.         }    
      19.         public FirstViewModel ()    
      20.         {    
      21.             LoadData ();    
      23.         }    
      25.         public async void LoadData()    
      26.         {    
      27.             INewsLoadingService service = new NewsLoadingService ();    
      28.             NewsCollection=new ObservableCollection<string>(await service.LoadNews ());    
      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();    
        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 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=""    
            3.     xmlns:local=""    
            4.     android:orientation="vertical"    
            5.     android:layout_width="fill_parent"    
            6.     android:layout_height="fill_parent">    
            8.     <TextView    
            9.         android:layout_width="fill_parent"    
            10.         android:layout_height="wrap_content"    
            11.         android:textSize="40dp"    
            12.         local:MvxBind="Text Title" />    
            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 to our ViewModel. One was Title and the other was 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.