Wednesday, November 13, 2013

ActionBarSherlock + Xamarin + MVVMCross


Short history of ActionBar in Android and Xamarin

1. ActionBar was first added in Android 3.0 (API Level 11).

2. ActionBarSherlock is a third-party library created by Jake Wharton, which brought ActionBar support for Android 2.x: “The library will automatically use the native action bar when appropriate or will automatically wrap a custom implementation around your layouts. This allows you to easily develop an application with an action bar for every version of Android from 2.x and up.”

ActionBarSherlock it’s not just about ActionBar support on Android 2.x, it also has some nice features not available in the Android’s ActionBar implementation.

3. In July 2013, Android Support Library revision 18 introduced a new v7 appcompat library which has ActionBar support for Android 2.1+.

4. Xamarin created a free component for their store as a binding for the ActionBarSherlock, called ‘ActionBarSherlock for Xamarin’.

5. Xamarin created a free component for the Android support Library v7 (rev 18)

I haven’t yet tried how the ActionBar works using the this support library.


Using ActionBar in Xamarin application with ActionBarSherlock Xamarin component

The steps are:

1. Create an Android application and add MvvmCross by NuGet. (MvvmCross creates and adds a FirstView activity to the project).

2. Add ActionBarSherlock for Xamarin component from Xamarin Components store

3. Make sure the Android project has ‘Compile using Android version’ and ‘Target Android version’ set to the latest Android version.

4. Add reference to Mono.Android.Support.v4

5. Add a MvvmCross implementation for SherlockFragmentActivity (MvxSherlockFragmentActivity).

   I create a folder ‘MvxSherlockActionBar’ in the Droid project and add to it these two files: MvxEventSourceSherlockFragmentActivity.cs MvxSherlockFragmentActivity.cs These add support for MvvmCross to SherlockActionBar.

6. Change the FirstView’s class parent from MvxActivity to MvxSherlockFragmentActivity and set the ActionBar’s theme

[Activity(Label = "View for FirstViewModel"] 
public class FirstView : MvxSherlockFragmentActivity
protected override void OnCreate(Bundle bundle)

You should use SherlockFragmentActivity::SupportActionBar property to use the ActionBar.

A very basic walkthrough to the Xamarin component: 
Xamarin also created a sample application using Xamarin ActionBarSherlock component and made its source code available It contains different examples of usage.


hub said...

How do you create a MvvmCross implementation of SherlockFragmentActivity (MvxSherlockFragmentActivity)?

Thank you.

Andrei Nitescu said...


not sure I understand your question.