Fragments and ViewPager with Mvx

I've been toying around with MvvmCross (Mvx) and Fragments lately and found out that my binding for the ViewPager is only working if you are using old type of Activities and Views. So in this blog post I will describe what I did to get the ViewPager to work nicely with Fragments and Mvx.

I have made some code samples which are shown in the bottom of this blog post and which I will refer to. So to start with, let me explain why this approach is necessary. There are currently no official bindings for the ViewPager for Mvx for Xamarin.Android. However, I did make one, and it works pretty well and binds to the ViewPager like you would with a ListView. In fact you can use different ItemTemplates such that you can display different kinds of Views inside the ViewPager. How to do that is decribed in the Working with Collections Tutorial in the MvvmCross Tutorials repository.
With Fragments that approach changes. Now a FragmentPagerAdapter is required, which creates instances of Fragments and keeps track of which are shown on the screen and which to cache, much in the same fashion as a normal Adapter for ListViews. However Fragments are a lot different as they have their own life-cycle and with Mvx each of them have their own ViewModel as well, just like you previously would have a ViewModel for an Activity. The binding of the View associated to a Fragment also happens inside that Fragment. So the binding action which previously was inside the Adapter, now is handled in the Fragment. This means a lot less work for me! So since I cannot use the bindings I previously made I had to come up with something new.

Anyways let us get to the fun stuff and let me explain the code below.
  • Home.axml is the Android View, which contains the ViewPager and an optional ViewPagerIndicator (will post source for this soon, look out for another blog post meanwhile you can use this) - very simple no bindings here.
  • HomeViewModel.cs is a simple ViewModel, similar to one you would use for a Tab kind of View, which instantiates other ViewModels to use for each tab, or in this case for each page in the ViewPager.
  • MvxViewPagerFragmentAdapter.cs is what we need to inform ViewPager about our Fragments. It needs to know about at least the Type of the Fragment and the ViewModel associated to it. The Title is just for convenience when using a ViewPagerIndicator. Basically what happens in GetItem is that a Fragment of a specific Type gets instantiated and the DataContext for that Fragment is set. This way the Fragment itself can create bindings to Properties and Commands internally. GetPageTitleFormatted is simple for a ViewPagerIndicator. FragmentJavaName and FragmentInfo was highly inspired by the MvxTabsFragmentActivity which kind of does the same thing as this Adapter but with a lot more stuff to make it work with a TabHost.
  • HomeView.cs now this last piece of code, simply creates the FragmentInfo instances for the Fragments I want to display in the ViewPager and gives that information to the Adapter which is set for the ViewPager.
This is basically it. See the video for a quick run through of the code and how it looks at the end of it.

Working with PCL's in the latest Xamarin.Android

Recently Xamarin released version 4.7.10 alpha of Xamarin.Android, which stated:
"PCL support!
(Cross your fingers, sacrifice your favorite meal under the full moon, and your PCL projects should Just Work! Testing wanted.)"
So I kind of wanted to find out if it really was true, and it also happens to be that I am doing a project which needs to fetch something from the Internet, which is great to test out HttpClient in PCL's as well. The project also uses Stuart Lodge's fantastic MvvmCross framework, also with the new PCL stuff, and everything seems to work. However there are some things you have to work around until Xamarin releases tooling that allows you to reference PCL's in your Android and iOS projects in the Visual Studio plugin.

So what I have tried:
  1. Download MvvmCross from the GitHub Repo, and rebuild the whole thing with the new Xamarin.Android version.
  2. Create a new PCL Library project in either Xamarin Studio or Visual Studio. I choose to target WP8, Store apps and .NET 4.5.
  3. Grabbed prerelease Microsoft.Net.Http package for the PCL. This also imports some Bcl stuff which allows you to use Async in the PCL. Now you should be able to use HttpClient and Async, sweet!
  4. For the Android project, here what is tricky. VS will complain that the Android project does not support PCL's, but it is lying! What you can do is either manually add a reference in the .csproj file or open up the project in Xamarin Studio and do it there.
  5. You will also have to grab the DLL's from the packages folder in your solution and import System.Net.Http, System.Net.Http.Extensions and System.Net.Http.Primitives from the Microsoft.Net.Http NuGet package you downloaded. I took if from the portable-net40+sl4+win8+wp71 folder.
  6. Now do your MvvmCross stuff, I just bound a button to a Command in my ViewModel, which calls a method in a service, which then in turn uses HttpClient to fetch some stuff from a Web Service.
This should also work for Xamarin.iOS and also on WP7 and WP8, Store Apps etc. As long as you use Microsofts BCL and Http packages in your projects.

Made a video describing the whole thing in more details:
Sample code can be found in my GitHub repo


I had a little time while watching the WEC race on Spa yesterday to port a pretty interesting View to work on Xamarin.Android. If you have ever played the Mario games, you might have noticed, that the background  moves slowly while the foreground moves faster while you advance in the level. This is basically what this View does. How it works is that the ParallaxScrollView scales the Background View to fit the parallax factor. So lets say the factor is 0.5, this will mean the Background View is half the size of the Foreground View's content. When you scroll the Foreground it will scroll the Background at half speed of the Foreground. Setting the factor to 1 scrolls both Views at the same speed. Setting it above one, scrolls the Background faster than the Foreground. To have it look good, a View that stretches well is recommended, such as a repeatable pattern or such.

I made a quick demo of the port, which is based on the original demo, only difference is that the Background View is a bit different.

You can find the ParallaxScrollView in my GitHub repo, I also plan to release it in the Xamarin Component Store soon.

Last but not least a shoutout to Christopher Jenkins (@chrisjenx) who originally made this View for Android and did all the hard work, I simply ported it to Xamarin.Android. Thanks a bunch for your work!

MonoDroid.ActionBar is now LegacyBar!

Behold! LegacyBar!

Ever since Xamarin renamed Mono for Android to Xamarin.Android with their Xamarin 2.0 release, I have been thinking of a new name for the MonoDroid.ActionBar project.

If you don't know MonoDroid.ActionBar, it is a project which aims to bring an ActionBar across all Android API levels all the way back to API 4! How do we do this? By making our own from scratch mimicking the built in into Android. It started as a quick and dirty port of the android-actionbar by Johan Nilson and quickly people from the Mono for Android community started using it and forking it and one day a guy named James Montemagno started making pull requests on GitHub. Ever since then James and I have been sparring and making changes to the ActionBar implementation.

Now that Xamarin has renamed Mono for Android to Xamarin.Android we thought it was time to rename our project too. Since the ActionBar is meant to support legacy versions of Android, why not call it LegacyBar? So from now on the project is called LegacyBar! My personal aim for LegacyBar from now on is to make it ready to put in the Xamarin Component store, make a bunch of documentation. When that is done extending it to support a lot more of the same things as the native Android ActionBar.

Stay tuned for more LegacyBar goodies and feel free to fork it on GitHub!

Adding images to TextView and EditText using Spannables in Mono for Android

I've just been playing around with Spannables in an attempt to help out a user on the Xamarin Forums, his topic is "Text With Image". Just from looking at that topic name, I thought: "Hey, he probably just want to show an image next to some text or something, this should be easy enough". Then I looked inside, and they guy actually wanted text inline with text when actually editing it. Now I thought: "How do I do that?!"
I think I have touched the concept of Spannables briefly before, when I helped a guy making a sub-part of a text bold or something, but I never thought they could be used for displaying images inline with text. I guess this is how it is done in all those messaging apps, which show emoticons. I decided to use that as a sample.

I started out with a super simple sample trying to get an Image shown in a TextView. I googled up some solutions and sure, Spannables allow using ImageSpan inside of them! There were nice samples and such, and I came up with this.
Easy, huh? And you can add loads of other Spans to the Spannable, such as StyleSpan, which you can style your fonts with bold, italic and other styles.

Since that was so easy, I quickly tried to do that with an EditText. It also works just fine, so moving on. How do I imitate those messaging apps, which replace ":-)" with an actual smiley. Now EditText has some nice events which you can listen to for changes. I listen for AfterTextChanged, from here I can get the Editable Property from the argument, which is essentially a Spannable you can edit and the changes will be reflected in the EditText. This is probably a good place to replace text with images.
Next I cooked up a class which holds a Dictionary of strings and ints. The string keys are the text representation of the smileys, i.e. :), :-), :D, :P and so on. The ints are the Android Resource ids for the Drawables representing the smileys. Then I have a method for replacing all the matches in the string with their respective Drawables. It looks like this.
Now you might notice I am removing all the images if they are present. This is because it is not possible to have two Spans at the same index in a Spannable, hence they need to be removed. Don't worry all the images are added at the end. This simply loops all the string matches in the Spannable and adds ImageSpans for the matches. Very simple. To get all the indices in a string which match I use a simple extension I found on StackOverflow.
Now the AddSmiles() method is hooked up to the AfterTextChanged event for the EditText, and voila. Text is replaced with images!
Pretty awesome smileys :-D 
The complete sample code can be found in this Gist:

You can also watch this video for a demonstration

For references on how to do this in Java I used: