Disclaimer: this is an automatic aggregator which pulls feeds and comments from many blogs of contributors that have contributed to the Mono project. The contents of these blog entries do not necessarily reflect Xamarin's position.

November 26

Video: Open Source Demo Xamarin.Forms App – VervetaCRM

upload (1)I love Xamarin.Forms.  It’s one of the core features released in Xamarin 3, giving you the ability to build beautiful, native UIs for iOS, Android, and Windows Phone from a single shared C# codebase.  To show Xamarin.Forms in action, we created a cloud-connected, fully functioning CRM app for iOS, Android and Windows Phone to demonstrate the power of Xamarin.Forms.  Today, we’re making the source code available to you.

VervetaCRM is a mobile CRM app for salespeople at a fictional office-supply company (named after the vervet monkey).  The app lets mobile salespeople track their sales performance, see their contacts, view customer location maps, and capture orders with user signatures.  Even with these complex, cross-platform requirements, we were able to get over 90% code re-use. Watch this short video in full-screen to dive into the code and see VervetaCRM working on iOS, Android and Windows Phone.

To fulfill enterprise requirements and add complex features, it relies on several components and libraries:

Azure Mobile Services: this app uses Azure Mobile Services (AMS) as the cloud backend for authentication and data.  It integrates with Azure Active Directory to create a consistent sign-on experience for mobile users.  The AMS component simplifies the implementation and uses oAuth to both authenticate a user and provide a token.

Data is synchronized with an Azure SQL cloud database and a SQLite database that runs on the device – providing fast, offline data access and a consistent data access API.

OxyPlot: this is an outstanding, open-source .NET-based plotting and charting library that shows sales performance with basic graphs.

Signature Pad: available from the Xamarin Component Store to capture and display user signatures.  This component highlights Xamarin.Forms extensibility; using custom renderers, it was easy to consume the platform-specific signature pad components into the Xamarin.Forms shared UI code.

Download the Code

The code is available for download on GitHub at https://github.com/xamarin/vervetacrm.

Learn More

Here are some additional links to help get you started with Xamarin.Forms apps:

Happy Thanksgiving!

4.6 is Released with Source for UI System!

ui-code-closeupToday, we are delighted to release the awesome Unity 4.6, which contains our new UI system as the headline feature. The release cycle has indeed been long, but we’ve taken the time needed to work with you to test the UI system and incorporate your feedback to ship a UI system that we’re really proud of.

Unity 4.6 also includes x86 support for Android – you can now select FAT, x86 or ARMv7 as a build target. This will allow you to export for x86 Android devices, like the new Nexus player from Google.

You can find out more details about what is included in Unity 4.6 on the Release Notes page.

Another Step for Our Open-Source Initiative

As promised, the source code for our UI system is live on BitBucket. Using the included solution file, you can build a UI module that will work as a drop-in replacement for the bundled UI system. To get started with building your own UI module, take a look at the repository’s README file. As always with our Open Source components, our UI system is released under an MIT/X11 license.

With the source being available, you’re free to customize and improve the UI system in whatever way makes sense to you (and also to share those changes with others). We love to work with our community — see the README file in the repository for information on our policy regarding pull requests.

For more information about our Open Source offerings and plans, take a look at some of our previous blog posts: More Open Source Initiatives from Unity and Getting Started as a Contributor to Our Open Source Projects.

Community: it’s now your move – time to show us what new awesome content you can create!

P.S. iOS ARM 64-bit is on the way

Don’t forget that as we announced here, we plan to ship a beta preview of our iOS ARM64-bit feature based on Unity 4.6.x in January 2015.

On October 20, Apple announced that, starting February 1, 2015, new iOS apps uploaded to the App Store must include 64-bit support. We’re very aware of people having nearly completed games on Unity 4.x and we’re working hard to deliver a solid solution for Unity 4.6.x.

Due to heavy code reuse, the preview of iOS ARM64-bit in Unity 4.6.x is expected to be on par with the Unity 5 implementation.

November 25

Android Tips: Hello Toolbar, Goodbye Action Bar

It seems like just yesterday that Google introduced the Action Bar for Android. It jump started a revolution for the Android user interface and made developer’s lives easier by providing a great way to provide menu options, tabs, and more for their users. With Android 5.0 Lollipop, all of this is about to change once again with the introduction of the Android Toolbar.

toolbar

You can think of the Toolbar as the Action Bar’s bigger sibling that has grown up and is free to roam around the house by itself. It’s a generalization of the Action Bar that isn’t bound to an Activity’s window decor, can be placed anywhere in the user interface, and can even be designated as the Action Bar replacement for an Activity. It’s highly customizable, which means you can add navigation buttons, branded logos, titles, subtitle, action menu items, or even your own custom views.

For this sample, I am going to focus on the Android 5.0 (v21) Toolbar. The same can be achieved using the new Support Library v7 AppCompat, which features a backwards compatible Toolbar and is available as a pre-release NuGet.

Applying Your Theme

We will start by applying the Material theme to our Android application, but we will now set two special attributes android:windowNoTitle and android:windowActionBar to tell Android we will be using a Toolbar instead of the Action Bar.

<style name="MyTheme" parent="@android:style/Theme.Material.Light.DarkActionBar">
    <item name="android:windowNoTitle">true</item>
    <!--We will be using the toolbar so no need to show ActionBar-->
    <item name="android:windowActionBar">false</item>
    <!-- Set theme colors from http://www.google.com/design/spec/style/color.html#color-color-palette-->
    <!-- colorPrimary is used for the default action bar background -->
    <item name="android:colorPrimary">#2196F3</item>
    <!-- colorPrimaryDark is used for the status bar -->
    <item name="android:colorPrimaryDark">#1976D2</item>
    <!-- colorAccent is used as the default value for colorControlActivated
         which is used to tint widgets -->
    <item name="android:colorAccent">#FF4081</item>
  	<!-- You can also set colorControlNormal, colorControlActivated
         colorControlHighlight and colorSwitchThumbNormal. -->
  </style>

If you want to learn more about the new themes, be sure to read my Introduction to Material Design blog post and watch my and Jérémie Laval’s sessions from Xamarin Evolve 2014 on Material Design.

Replacing the Action Bar

With our theme attributes set, we can now create our first layout. The Toolbar can be found in your Android Designer’s toolbox, from which you can simply drag and drop it at the top of your layout. Often you will want to use a RelativeLayout to specify that your Toolbar is at the very top.

<Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?android:attr/actionBarSize"
    android:background="?android:attr/colorPrimary" />

Now in your OnCreate method of your activity, you will need to find your Toolbar. To have it mimic the old ActionBar, you can set a new method call SetActionBar(Toolbar toolbar);.

protected override void OnCreate (Bundle bundle)
{
  base.OnCreate (bundle);
  SetContentView (Resource.Layout.Main);
  var toolbar = FindViewById<Toolbar> (Resource.Id.toolbar);
  //Toolbar will now take on default Action Bar characteristics
  SetActionBar (toolbar);
  //You can now use and reference the ActionBar
  ActionBar.Title = "Hello from Toolbar";
}

ToolbarNoTheme

This is the easiest way to transition from the ActionBar to the new Toolbar, as all of your existing Action Bar menus will automatically work if you are inflating them in your OnCreateOptionsMenu method.

Applying Themes

Since the Toolbar is independent, it can also be themed independently as well. The android:theme is the main theme of the bar, and android:popupTheme is the theme to apply to menu item pop ups. If you are using a light theme, or want the look of a dark Action Bar, you can apply two themes directly on the Toolbar, which would look like this:

<Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?android:attr/actionBarSize"
    android:background="?android:attr/colorPrimary"
    android:theme="@android:style/ThemeOverlay.Material.Dark.ActionBar"
    android:popupTheme="@android:style/ThemeOverlay.Material.Light" />

ToolbarThemedNormal

ToolbarPopOver

Custom Action Bars

As I mentioned earlier, the real reason to upgrade to the new Toolbar is that it has complete freedom to be placed where you want it and is fully customizable; it can even have a completely separate action menu that you can manage. Let’s say you want to put a Toolbar at the bottom of your screen and theme it in an accent color. You would simply add another Toolbar widget to the bottom and apply a different theme to it:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <!--First Toolbar goes here-->
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@id/toolbar">
        <!--Other widgets-->
        <!--Custom second toolbar at the bottom with an accent color for the background.
            Additionally, you can set any custom property and make the height larger or smaller.-->
        <Toolbar
            android:id="@+id/toolbar_bottom"
            android:minHeight="?android:attr/actionBarSize"
            android:background="?android:attr/colorAccent"
            android:theme="@android:style/ThemeOverlay.Material.Dark.ActionBar"
            android:popupTheme="@android:style/ThemeOverlay.Material.Light"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </LinearLayout>
</RelativeLayout>

Back in the Activity, the last step is to find this new Toolbar. Once found, we will not set it as an Action Bar, but instead we’ll inflate a separate menu and implement a new click handler when the users interact with it.

var toolbarBottom = FindViewById<Toolbar> (Resource.Id.toolbar_bottom);
toolbarBottom.Title = "Photo Editing";
toolbarBottom.InflateMenu (Resource.Menu.photo_edit);
//Add menu click handler
toolbarBottom.MenuItemClick += (sender, e) => {
  Toast.MakeText(this, "Bottom toolbar pressed: " + e.Item.TitleFormatted, ToastLength.Short).Show();
};

Multiple Android Toolbars

Going Further

The new Android Toolbar allows for a highly customizable developer experience that we never had access to with the standard Action Bar. You can grab the source code for this example and try out other Android L features on our Samples Gallery.

Two Hot New Features for Calca

See Calca 1.3 on the Mac App Store

Calca 1.3 has hit the Mac App Store and it contains two features that I hope you’ll love: plotting and quick entry.

Plotting

When Calca was first released, I was asked a great question by Jason Brennan:

Do you think plotting is an essential function missing (most of) today’s “calculators”?

My answer was an unequivocal “YES!” followed by a lament for having cut it from v1.0 (#irony). A year passed and plotting became the #1 voted feature for Calca.

Well plotting has finally arrived! You can now create as many plots as you want, each with multiple series. To do it, just pass a function to the plot function. For example, I can plot a sine wave at 5 Hz with:

plot(sin(5t * 2pi))

Passing multiple arguments generates multiple series:

plot(sin(5t * 2pi), cos(5t * 2pi))

You can also plot data!

plot([-1, pi, 0, 2])

The plots are displayed in the right margin of the application and support mouse tracing, zooming, panning, and even export as CSV or SVG.

All plots are displayed as 2D line graphs and are drawn using Calca’s standard colors. The area under the curve - the integral - is always displayed as it gives quick visual indication of whether your data is positive or negative. Also, I think it looks pretty.

When you run Calca, go to Help and choose Plots for more details and examples.

More formatting options and more plot types will be added in the future, but I couldn’t let this feature go unreleased any longer. I’m looking for your feedback! Now that we have plotting, I want to know what kind of plots you make so Calca can help you better in the future.

Quick Entry

Calca is certainly a powerful “math document” editor, but sometimes you just want to do some quick math.

I often find myself in another app needing to do some quick calculations. Of course I could switch over to Calca, create a new document, do my work and switch back to that app. These aren’t hard steps, but they wear on the soul.

The truth is, I found myself falling back to Spotlight for these quick computations - you can’t argue with efficiency! But I missed Calca, I missed its symbolic nature, its units, its functions.

No More! Calca now has a UI mode that is very similar to Spotlight’s. When Calca is running, simply hit the global keyboard shortcut ⇧⌘C (of course you can change this) and you will be greeted with a little centered window all ready for you. Just start typing and Calca will happily perform your calculations and display the last one in the bottom half of the window. It makes computations in other apps fast and easy.

This has changed everything for me and is, honestly, my primary way of interacting with Calca now. I almost always start my work in the quick entry window and quite often just stay there. Only when the window gets to be too unwieldy do I hit ⌘N to start working on a new document with that math. It’s a great workflow that I hope you’ll love.

One More Thing

There has been this terribly annoying bug in Calca that resulted in text jumping around when editing long documents. That bug is dead now. Squashed. Eradicated. It will plague us no more.

What about iOS and Windows?

They’re coming!

November 24

Adding Intelligent Analytics and Crash Reporting to Your Apps

At this year’s Xamarin Evolve 2014 we announced Xamarin Insights, a real-time monitoring solution allowing developers to improve their apps by reporting crashes and exceptions. Xamarin Insights MonitorGetting started with Xamarin Insights is as simple as adding just one line of code to your mobile apps, but you can gain even more information by optionally monitoring session, user, and event data.

Creating Your Insights App

To get started, just head over to insights.xamarin.com and log in to your Xamarin account. Once you are logged in, you will see the “Add New App” button in the top right.

Add New App Insights

This will navigate you to a new page where you need to name the app that you would like to monitor. You will also see an API Key that you will use inside of your app to start monitoring, so keep this handy. When you have filled in all of the information, click the Create New App button.

You can always get back to this information by selecting the settings option inside of an existing app.

Adding Insights to Your App

Insights LogoXamarin Insights supports a wide range of mobile and desktop platforms, including iOS, Android, and Mac apps built with Xamarin. In addition to these, Insights also supports all of the Windows platforms including Windows Phone, Windows Store, and desktop apps. There is even a Portable Class Library that enables you to add reporting to all of your apps from your shared app logic. I’m going to cover iOS, Android, and Windows Phone, however, be sure to read the full API Documentation on how to add other platforms.

To get going, you are able to add Insights through a convenient NuGet package or through the Component Store in Xamarin Studio or Visual Studio.

Install Insights NuGet

With the NuGet or Component installed in your project, you just need to call the Initialization code in each platform to automatically start receiving native and managed crash reporting and usage statistics about your app.

Android

You will want to call the Initialize code where your app starts, such as your main Activity or a custom Application’s OnCreate method. In addition, make sure you have the Internet permission enabled in your AndroidManifest.xml file.

Xamarin.Insights.Initialize("Your API key", yourAppContext);

iOS

Simply place the Initialize call in your AppDelegate’s FinishedLaunching method:

Xamarin.Insights.Initialize("Your API key");

Windows Phone

All Windows Phone apps have an App.xaml.cs file that contains the main constructor for the app. This is where you will place the Initialization call.

Xamarin.Insights.Initialize("Your API key");

With this single line of code, your app is set up and ready to go! Once your app is launched, you will start to receive data in your Xamarin Insights Dashboard.

Insights Data

Exception and Warning Reporting

Even though you automatically get crash reporting with the Initialization code in place, you might want to get even deeper insights into where your app is having issues and warnings are caught, or add data to exceptions that are caught and re-thrown.

Insight Warnings

Reporting an exception as a warning is as simple as calling the Report method to pass in the exception:

try {
  ExceptionThrowingFunction();
}
catch (Exception exception) {
  Xamarin.Insights.Report(exception);
}

You can add additional data to the exception being caught as well by passing in a Dictionary of string key value pairs:

try {
  ExceptionThrowingFunction();
}
catch (Exception exception) {
  Xamarin.Insights.Report(exception, new Dictionary <string, string> {
    {"Event Id", "00113"},
    {"Other Data", "Goes Here"}
  });
}

If you want a warning to bubble up the stack to be handled later, you can still add additional data to the exception by using the exception’s Data field.

try {
    ExceptionThrowingFunction();
}
catch (Exception exception) {
    exception.Data["AccountType"] = "standard";
    throw;
}

Event Tracking

Receiving the full stack trace is great for seeing the root of the issue. However, how do you know what steps your users were taking leading up to the crash? This is where event tracking comes in extremely handy. You are able to track any event with a simple method call.

Xamarin.Insights.Track("QuestCompleted", new Dictionary<string, string> {
    { "Quest", CurrentQuest.ToString() },
  });

Now, when a crash occurs, you will see any event that has also been tracked to help you reproduce the crash.

Session Crash

So Much More

There is so much to Xamarin Insights – including real time usage statistics, identifying information about your users, communication preferences, popular service integration such as GitHub and Visual Studio Online, e-mail notifications, and so much more – that I can’t cover it all in a single blog post. Be sure to browse through the Xamarin Insights Documentation and watch the Xamarin Evolve 2014 keynote to see Insights in action.

Sustained Engineering Plan For Unity 4.5 and 4.6

Great news! The 4.6.0 public release is going live later this week. When that happens, the default Unity version will become 4.6.x.

Subsequent releases of 4.6.x will be handled by Sustained Engineering through the usual process of weekly patch and monthly public releases. The first patch (4.6.0p1) will be released on December 4, and the first public version (4.6.1) will be released soon after.

The following summarises the 4.5.x to 4.6.x transition plan and which version is going to contain what fix:

sM65bqDY_cmtE3cd6H5DJbQ

  • Unity 4.5.5 (released on October 13 2014) will be the last public release version of Unity 4.5.x.

  • All bugs fixed and released in 4.5.5p1 to 4.5.5p5 will be available in 4.6.0p1 and subsequently in  4.6.1.

  • In addition, a few other issues including iOS 8 autorotation are in the works and will be included in 4.6.0p1 and hence in 4.6.1.

  • The first patch release (4.6.0p1) will be shipped on December 4.

  • The first public release (4.6.1) will go live soon after 4.6.0p1.

  • Note that 4.6.0 will use the Web Player released in 4.5.5. New updates to the Web Player (including the OSX 64-bit plugin) will be available in 4.6.1. This version will also be available for automatic updates.

  • Technically, all bugs fixed with Milestones 4.5.6 on the Issue Tracker should be considered as fixed in 4.6.1 as there will not be any 4.5.6 public release.

  • Future 4.5.5 patches will be released only when the need arises – e.g. serious issues affecting wider community and/or to honor existing support contracts.

  • More importantly, iOS 64-bit support will be available in a future 4.6.x release. Learn more

In summary, anyone who would like to ship games with Web Player support with bugs fixed in 4.5.5p1-4.5.5p5 should wait for the 4.6.1 public release. This will be shipped soon after 4.6.0p1. Note that 4.6.0 does not include fixes from the patches 4.5.5p1-4.5.5p5. Also due to complications that could arise from shipping two public releases close to each other, it was decided to drop 4.5.6 and do a 4.6.1 public release instead.

November 23

Android Material Image Loading

Among the plethora of seemingly impossible things in the Material Design specification, there is one that piqued my curiosity this morning.

It’s something everybody does at least once, if not everywhere, in his app which is loading and transitioning images.

Now to make this more glamour we generally all went with the classical, battle-tested approach of shifting the opacity of our image container to announce the change (that was even one of my first Android tip).

But the new approach taken by Material and detailed in the “Loading Images” section goes a lot further than this by also throwing some image levels manipulation in the mix.

The process is summarized in the following graph:

It outlines a 3-steps process where a combination of opacity, contrast/luminosity and saturation is used in concert to help salvage our poor users eyesight.

Android has always supported image manipulation through the ColorFilter class that can be set on any drawable and on some view classes (ImageView for instance).

When used with its 4x5 ColorMatrix-based implementation ColorMatrixColorFilter, you can virtually implement any kind of image transformation provided you grok the way vector/matrix multiplication work (head to the ColorMatrix documentation for the resulting equations).

The only thing that was a limiting factor is that a filter is initialized once and for all. If you want to change the effect you need to create a new instance of the filter (which initialize a native counterpart) and replace the old version with the new one.

Obviously this is a complete downer when you do animations because you don’t want to stress out the GC and GPU during those phases by creating a new instance of the filter at every refresh step.

But thanks to Lollipop and the fact that @hide can’t stop us, there is actually a new public method allowing us to update a filter after the fact.

Armed with this knowledge, we can now set out to create a custom ITypeEvaluator to tweak our filter:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Refer to http://developer.android.com/reference/android/graphics/ColorMatrix.html
// for a list of the matrix indexes
class AlphaSatColorMatrixEvaluator : Java.Lang.Object, ITypeEvaluator
{
	ColorMatrix colorMatrix = new ColorMatrix ();
	float[] elements = new float[20];

	public ColorMatrix ColorMatrix {
		get { return colorMatrix; }
	}

	public Java.Lang.Object Evaluate (float fraction, Java.Lang.Object startValue, Java.Lang.Object endValue)
	{
		// There are 3 phases so we multiply fraction by that amount
		var phase = fraction * 3;

		// Compute the alpha change over period [0, 2]
		var alpha = Math.Min (phase, 2f) / 2f;
		elements [19] = (float)Math.Round (alpha * 255);

		// We substract to make the picture look darker, it will automatically clamp
		// This is spread over period [0, 2.5]
		const int MaxBlacker = 100;
		var blackening = (float)Math.Round ((1 - Math.Min (phase, 2.5f) / 2.5f) * MaxBlacker);
		elements [4] = elements [9] = elements [14] = -blackening;

		// Finally we desaturate over [0, 3], taken from ColorMatrix.SetSaturation
		float invSat = 1 - Math.Max (0.2f, fraction);
		float R = 0.213f * invSat;
		float G = 0.715f * invSat;
		float B = 0.072f * invSat;

		elements[0] = R + fraction; elements[1] = G;            elements[2] = B;
		elements[5] = R;            elements[6] = G + fraction; elements[7] = B;
		elements[10] = R;           elements[11] = G;           elements[12] = B + fraction;

		colorMatrix.Set (elements);
		return colorMatrix;
	}
}

Here is how you can set it up:

1
2
3
4
5
6
7
8
9
10
11
12
var imageView = FindViewById<ImageView> (Resource.Id.image);
var drawable = (BitmapDrawable)Resources.GetDrawable (Resource.Drawable.monkey);
var evaluator = new AlphaSatColorMatrixEvaluator ();
var filter = new ColorMatrixColorFilter (evaluator.ColorMatrix);
drawable.SetColorFilter (filter);

var animator = ObjectAnimator.OfObject (filter, "colorMatrix", evaluator,
                                        evaluator.ColorMatrix,
                                        evaluator.ColorMatrix);
animator.Update += (sender, e) => drawable.SetColorFilter (filter);
animator.SetDuration (2500);
animator.Start ();

And here is the result:

It’s probably safe to assume Google will come out with an official way for this pattern e.g. in a subsequent support library update. In the meantime, you can get cracking with this version.

November 21

Use a PIN code instead of password on your Surface Pro (or other Windows touch device)

Here are step instruction on how to replace the Windows login password prompt with a PIN code, especially on those yummy new Windows tablets (I am looking at you Surface Pro 3):

2014-11-21_21-32-422014-11-21_21-33-38  2014-11-21_21-33-582014-11-21_21-34-33

 

 

Get Started with Xamarin.Forms via the Evolve Mini-Hack

As part of the Evolve Darwin Lounge, we had a bunch of small coding exercises for a variety of topics that attendees could complete to win a prize. One of the mini-hacks from Evolve 2014 involved creating a simple application with Xamarin.Forms. This is a nice example to try out Xamarin.Forms yourself.

Let’s take look at how to do this mini-hack. We’ll be creating the Magic 8 ball application shown below:

app screenshot

1. Create a new Xamarin.Forms solution called MagicBall (I’m using the PCL project here):

new solution

2. Add a ContentPage named BallPage to the shared project:

content page

3. Edit BallPage.xaml to contain a StackLayout with an Image, Label and Button respectively. Also add some padding to the top of the page:

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage
  xmlns="http://xamarin.com/schemas/2014/forms"
  xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
  x:Class="MagicBall.BallPage"
  Padding="0, 30, 0, 0">
  <ContentPage.Content>
    <StackLayout>
      <Image Source="ball.png"></Image>
      <Label x:Name="label" Text="Magic 8 Ball" Font="Large"
        HorizontalOptions="Center" VerticalOptions="CenterAndExpand" />
      <Button x:Name="button" Text="Tell Me!" HorizontalOptions="Center"
        VerticalOptions="CenterAndExpand" Clicked="ButtonClicked" />
    </StackLayout>
  </ContentPage.Content>
</ContentPage>

4. Add code to BallPage.xaml.cs to update the label randomly from an array of strings when the button is clicked:

public partial class BallPage : ContentPage
{
  string[] options = {" It is certain"
        , " It is decidedly so"
        , " Without a doubt"
        , " Yes definitely"
        , " You may rely on it"
        , " As I see it, yes"
        , " Most likely"
        , " Outlook good"
        , " Yes"
        , " Signs point to yes"
        , " Reply hazy try again"
        , " Ask again later"
        , " Better not tell you now"
        , " Cannot predict now"
        , " Concentrate and ask again"
        , " Don't count on it"
        , " My reply is no"
        , " My sources say no"
        , " Outlook not so good"
        , " Very doubtful "
  };
  public BallPage ()
  {
    InitializeComponent ();
  }
  void ButtonClicked (object sender, EventArgs args)
  {
    label.Text = options [new Random ().Next (options.Length - 1)];
  }
}

5. Update App.cs to return a BallPage:

public class App
{
  public static Page GetMainPage ()
  {
    return new BallPage ();
  }
}

6. Add the ball.png image to the Resources folder on iOS and Resources/drawable on Android.

7. Run the application and ask the 8 ball for advice.

The code for this mini-hack is available here: https://github.com/xamarin/mini-hacks/tree/master/Xamarin.Forms/solution/MagicBall

Update:
Craig Dunn has a solution in his repo that includes a Windows Phone project as well.

November 20

Apple iOS 64-bit support in Unity

Technology and hardware moves fast these days! Many of you will have seen by now the announcement that Apple made to developers on October 20.

Starting February 1, 2015, new iOS apps uploaded to the App Store must include 64-bit support and be built with the iOS 8 SDK, included in Xcode 6 or later. To enable 64-bit in your project, we recommend using the default Xcode build setting of “Standard architectures” to build a single binary with both 32-bit and 64-bit code.

So what does this mean for you mobile developers? Starting in February, your newly released games (and other apps) will need to take advantage of iOS 8 SDK and the new 64-bit ARM chips in newer iOS devices.

The good news is that we already support iOS 8 and have been hard at work on our 64-bit iOS solution for some months. The solution is IL2CPP.

What is IL2CPP?

Most of you will know that we’ve been developing our own runtime solution, IL2CPP, for quite a while now. It allows a range of flexibility for developers and internally here at Unity. We’re expecting big increases in performance experienced by end users as well. In short, we’re very excited about it.

IL2CPP came about when we were investigating how to approach WebGL while we were also researching new ways to make continued support for various platforms more efficient. The runtime combines an ahead of time compiler with a virtual machine to convert assemblies to C++ while leveraging standard platform C++ compilers to produce native binaries. The result are games and apps that run at native speeds. It allows us to push new core features to all of our supported platforms at the same time for a much more efficient schedule of updates. For a complete rundown of the technology, please see our previous blog post “The Future of Scripting in Unity”.

We’ve already seen tremendous results in WebGL and are expecting big increases in performance across all of Unity’s supported platforms, including iOS, which is already in development.

When can I get my hands on the tech?

IL2CPP is already being used for WebGL and if you’ve seen any of the Unity-authored WebGL demos, you’ve seen it in action. Hot on WebGL’s heels is iOS. In the next few weeks, first Unity 5 based alpha builds of the iOS ARM64 preview using IL2CPP are going to be released to closed alpha testing group. Shortly after, it will be made available to our closed beta groups.

Once we’ve had a round of intense and focused testing, we’ll roll the beta preview out to the pre-order beta group. The timeline for that completely depends on how that initial round of testing goes. We think it’s reasonable to plan a beta for pre-order customers and subscribers for January 2015.

The official release of iOS ARM 64-bit feature preview in Unity 5 series depends on the Unity 5 launch schedule, so we can’t say much about a specific timeline.The preview can be expected to run games with scripting of medium complexity.

[UPDATE] The term “medium complexity” was a bit too ambiguous. To clarify, we are confident that the majority of iOS projects will work with little or no modifications. There is a chance that some infrequently used functionality is currently incomplete or contains bugs. These issues will be addressed and resolved quickly. We are currently testing a range of iOS games and will keep you updated on progress leading up to the February deadline.

What about 4.6?

We have begun work on supporting that version as well. Unity 4.6 recently entered Release Candidate cycle, so it is going to be out really soon now. The plan right now is to ship beta preview of iOS ARM64-bit feature based on Unity 4.6.x before the February deadline. We’re very aware of people having nearly completed games on Unity 4.x and we’re working hard to deliver a solid solution for Unity 4.6. Due to heavy code reuse, the preview of iOS ARM64-bit in Unity 4.6.x is expected to be on par with Unity 5 implementation: games with scripting of medium complexity will be able to run.

What about earlier than 4.6?

We will not add iOS 64-bit support for versions of Unity prior to Unity 4.6. Bringing this technology to older versions of Unity is getting exponentially more difficult due to large differences in codebase. In order to ship iOS 64-bit apps support as soon as possible we chose to focus only on latest Unity 4.x version – 4.6. If you have unreleased games currently in production that are still being developed in an older Unity 4.x version, you will need to upgrade either to Unity 4.6.x or Unity 5 in order to publish it on the iOS App Store. Please note you can update 32 bit apps already released on the iOS App Store with any Unity 4.x or Unity 5 version. There is no requirement of 64-bit for games and apps already published on iOS App Store before the February deadline.

Will I be able to ship my game on time?

Your success is our entire reason for being, so we’re pushing hard to get everything ready on time. The best approach to be ready is to start testing early, so we encourage you to get a public preview in January and start upgrading.

If you’re working on something very complex, it will likely take a little while longer to have everything in place but you should be good to go if you’re targeting April.

We’re really, really happy with where IL2CPP is already and where it’s going!
It’s going to make a big difference not only to performance in games, but also in how quickly we can develop and share new features to all of you in the community.

Summary Q&A

What does this mean for my existing apps?
Nothing in the short term. Apple will not be removing any apps that don’t comply with 64-bit that have been uploaded and made available for sale before February 1, 2015.

What if I need to update my apps after the deadline?
The current word from Apple is that existing games and apps will not need to include support for iOS 8 and 64-bit architecture at the February 1, 2015 deadline. It’s important to note that while Apple has confirmed this, there is still the possibility that all apps need to support iOS 8 and 64-bit at a separate date down the line.

What if I’m planning to release after Feb 1?
Then you’ll need to comply with Apple’s demands. New apps will need to support iOS 8 and 64-bit architecture to ensure they’re making the most out of new iOS devices. For assistance from Apple developer support, visit https://developer.apple.com/contact/.

Real-Time Code Iteration with Sketches

Sketches are a powerful new feature that we announced as a preview release at Xamarin Evolve in October. With Sketches, developers can iterate on code within Xamarin Studio and immediately see the results, without having to go through a full build and deploy cycle.

Sketches

A sketch is a file that stands alone or can be contained in a project, making it easy to move experimental code from a sketch into a code base. In some ways, it’s the immediate window on steroids.

For example, say you want to inspect the result of some code such as :

var x = 1;
var y = 2;
var z = x + y;

Sketches use a REPL (read–eval–print loop) that evaluates the code and displays the results:

sketch results

Viewing Output

There are visualizers for the output built in, too. For instance, a color is displayed as shown below:

color visualizer

You can even pin the results to the output area:

color output

Additionally, the output can display graphs of data:

output graph

Visualizing Images

The visualizer can display other types of data, too, such as images:

image visualization

Graphics Code

Having image support is nice, because it allows you to write arbitrary graphics code in a sketch and render it to an image. For example, here’s a code snippet from a blog post I wrote a while back, showing the rendering of some Core Graphics drawing code (updated for the unified API) in an iOS sketch:

// Sketch your next great idea!
using UIKit;
using Foundation;
using CoreGraphics;
//
UIGraphics.BeginImageContext (new CGSize (320.0f, 300.0f));
using (var gctx = UIGraphics.GetCurrentContext ()){
  gctx.SetLineWidth(4);
  UIColor.Purple.SetFill ();
  UIColor.Black.SetStroke ();
  var path = new CGPath ();
  path.AddLines(new CGPoint[]{
    new CGPoint(100,200),
    new CGPoint(160,100),
    new CGPoint(220,200)});
  path.CloseSubpath();
  gctx.AddPath(path);
  gctx.DrawPath(CGPathDrawingMode.FillStroke);
}
var image = UIGraphics.GetImageFromCurrentImageContext ();
UIGraphics.EndImageContext ();

This renders a triangle in the sketch, as shown below:

Core Graphics sketch

Visualizing Views

Visualizers aren’t limited to just images. You can display views as well, such as a UIView on iOS or an NSView on OS X. For example, here is an NSBox with a border:

view visualization

Where sketches start getting even more compelling is when you start using them to modify code running in the iOS simulator and the Xamarin Android Player. For example, here is some Xamarin.Forms code created on the fly in a sketch, running in the Android Player:

forms sketch

To learn more about Sketches, check out the documentation in our developer center and the Sketches’ samples. Also see Aaron Bockover‘s great talk from Evolve.

Help Test the Future of Xamarin.Mac

Xamarin.Mac and Xamarin.iOS have always been close sister projects, sharing much of their underlying tooling and infrastructure. One of the features in the upcoming version of Xamarin.Mac that we are very excited about is the runtime unification.

Underlying any application that uses Xamarin.Mac (or Xamarin.iOS) is a runtime that manages interactions with the objective-c runtime. It handles exposing your C# objects to objective-c and your calls into various Apple APIs. Up until now we had two separate runtimes, one for iOS and one for OS X.

The runtime unification effort changes that, we now have the same runtime powering our Mac and iOS products. This will bring bug fixes and performance work done on iOS to OS X and enable many of the features that were pioneered in iOS to come to the Mac platform,  such as the new refcount system.

While we have worked hard to test these runtime changes internally, such a far reaching change has the potential to introduce bugs in many places.

We are releasing a preview version of the upcoming Xamarin.Mac to the alpha channel for an extended period of time for testing.

While the runtime unification work is the major feature of this preview release, this alpha also adds support for these 64-bit frameworks:

  • Accounts
  • GameController
  • EventKit
  • MapKit
  • MediaAccessibility

in addition to the frameworks provided in the previous alphas:

  • CloudKit
  • GLKit
  • JavaScriptCore
  • LocalAuthentication
  • SpriteKit

We are asking you to test your applications with it and report any issues you might find.

November 19

Xamarin Insights and the Azure Outage

On November 18, 2014 at about 5:00PM PST, Xamarin Insights experienced a service disruption due to a worldwide outage of Microsoft Azure. In addition, we had been experiencing partial outages at least 5 hours prior to this.

Even though Azure suffered a catastrophic storage failure, our event collection API – the web service that receives telemetry from every mobile app that has the Insights client library running – was able to receive and store reports during the entire outage. This means that we experienced zero data loss during this down time.

Even if our event collection API had been overwhelmed or inoperative, the Xamarin Insights client library has a smart queueing system which queues reports locally on end-user devices, and sends them once service is restored.

Our services that process the telemetry data have fully caught up on the backlog of data that was collected during the Azure outage. The aggregate statistics displayed in the graphs and various “counts” are lagging about an hour behind, but will continue to catch up throughout the rest of the day.

Insights - Azure

A graph showing the backlog of telemetry data. Notice the 3 minor hiccups before the outage.

Our goal with Xamarin Insights is to provide a real-time, comprehensive app monitoring service that helps you understand exactly how well your app is performing. We are gratified that the architectural decisions we’ve made so far have paid off in challenging circumstances, and we’ve learned a lot from this outage about how we can improve Insights in the future.

To learn more about Xamarin Insights to add real-time monitoring to your mobile applications check out xamarin.com/insights.

New Development Snapshot

Getting closer to a release.

Changes:

  • Optimized ForkJoinPool unsafe usage.
  • Optimized java.lang.[Integer|Long].[compare|divide|remainder]Unsigned().
  • Bug fix. Default interface methods should not conflict with their own base interfaces.
  • Bug fix. Miranda method in base class should not interfere with default interface methods.
  • Bug fix. Conflicting default interface methods should throw IncompatibleClassChangeError instead of AbstractMethodError.
  • Bug fix. LockSupport.parkUntil() didn't convert milliseconds to nanoseconds.
  • Implemented TwoStacksPlainDatagramSocketImpl.socketLocalAddress() and TwoStacksPlainDatagramSocketImpl.isAdapterIpv6Enabled().
  • Made sun.misc.Unsafe interlocked operations truly atomic (except for unaligned array access and int/long array access on different array types).
  • Made sun.misc.Unsafe array access more compatible with JDK. It is now possible to get/set primitive values from arrays of a different (primitive) type.
  • Fixed font file clean up issue on Windows 8.
  • Bug fix. NetGraphicsDevice.getDefaultConfiguration() should take the screen into account. Thanks to Maria Papendieck for this fix.
  • Bug fix. NetComponentPeer.getLocationOnScreen() should take insets into account. Thanks to Maria Papendieck for this fix.

Binaries available here: ikvmbin-8.0.5436.zip

Porting to Unity 5 – The Untold Rust Journey

Facepunch Studio’s founder Garry Newman and his team have been porting Rust over to Unity 5. How did it go? This blog post tells the yet untold Journey of Rust. Do you dare to journey with us?!

Working in the Unity field I get to meet lots of talented developers who use our engine. I’ve been supporting Facepunch Studios with the port and I thought that their experience was worth sharing. So I asked Garry Newman a few questions.

How big a part has Unity had to play in the success of Rust so far?

The only other engine I used was the Source Engine, which is like very different from Unity. You can change a texture, a material or a model and this instantly updates. Having 3DS Max or Photoshop open on another monitor making edits which is instantly reflected in Unity. This saves us about a minute of work. Over a span of 6 months that’s a massive deal for us. With the other engine, I would have to quit the game and reload it every time. Unity actually makes it fun to tweak things and you’re more likely to experiment just to find different ways of doing stuff.

How long did it take to port Rust to Unity 5?

It was probably about two hours, there wasn’t really much to it. Unity updated all our code automatically, in an instant. There were some issues with add-ons from the Asset Store that didn’t update right. We already hired the developer and he updated his plug-ins for us, so that problem was solved.

There’s a new system in Unity 5 that gives you a bit more control over plugins and dll libraries. At first, that freaked us out a bit, but soon we understood that it just means that we don’t have to put these things in these folders.

Of course, if you want to use the new shader system and stuff, you’ve got to actually go through all your content and update the materials and everything. If you want it to  look like Unity 4, you just update and it works.

But to implement the new standard shader and lighting system has been a longer process?

The artists had to realise that there’s a new system there. It’s a new way of working, really. They use the new Substance Painter, because it’s a bit more accurate with the actual inputs. Once they figured it all out, they are getting better results and they don’t have to work so hard to get good-looking scenes.

Screenshot_14

What was the first thing you wanted to change in Rust with Unity 5?

We wanted to see how good looking materials we could get, so we looked at making dynamic reflections and things like that to basically use all the new features in the new renderer.
It’s still an on-going process, we always go back to our materials and tweak. We will see a screenshot and see that it looks crap and we will update it.

What do you think about the other workflows with Unity 5?

It seems about the same really, though there are still some annoyances like adding events to animations. The audio stuff, that loads better. The material stuff seems a bit more complicated at first, but once you understand what the system is and how it’s working, it’s a lot easier. The new shading system is really good for making a material as you don’t have to choose a specific shader. If you want a normal map, you just add it and it works.

Touching on the Audio side of things, we have made a massive improvement there, how have you liked using it?

To be honest, we have only started using it. For now, we’re only using it to balance the volume for specific sounds like the footsteps. But it’s going to be useful moving forward when we start to add effects and things. I like that you can assign a variable to some of the parameters, it’s going to be really useful for volume controls. For example, if you’re in a cave, the sound will echo.

None of us are really audio guys, half the words on there we don’t really understand, but we will get to it.

Which Unity 5 feature had the biggest impact so far?

It was the PhysX upgrade. In Rust, we kept hitting the 65,000 collider limit on our servers, so we had all types of hacks to merge all these colliders together so it was really slow. Now there’s no limit now really, it’s perfect. The new PhysX system seems overall a lot faster.

We were having a lot problems with physics in Unity 4, for example, you had to add a rigidbody to a collider. If you moved a static collider, this added like half a seconds worth of lag. Now you can move stuff as you want and it’s free. It’s perfect for us because I’m not a fan of having hacky code.

2014-06-27_20-06-45

So the PhysX update helps the end users as well as development workflows?

Yeah, they probably don’t realise it, but it really makes a difference. For example, when you moved from one section to the other in the old Rust, you used to get a couple of seconds of lag when we rebuilt all the physics colliders. That doesn’t happen now, there’s a lot more freedom for us.

Are there three top porting tips you’d like to share?

There’s a good video on the new shading system that explains exactly what all the inputs are. You shouldn’t just try to eyeball it, as there are actual scientific values you can use.

Check your dll’s and ensure the settings are right on them.

There’s an upgrade guide on the beta page, which you should read as this pretty much highlights everything you need to do.

Final question, what’s next for Facepunch Studio’s?

Pretty much the same as we are doing now, Rust is a long term project. Garry’s Mod is nearly ten years old and we’re doing a similar thing with Rust. We have a few prototypes in the works though.

Anything else you want to share about Unity 5 or Rust?

Just thanks for making Unity I suppose, it’s just made our jobs easier and more fun compared to the old days.

Rust is a hugely popular game and is available on Steam for PC, Mac and Linux. It was a pleasure chatting to Garry about Rust and I look forward to it’s continued development with Unity 5.

2014-07-11_20-15-14

Live Webinar: Mobile Enterprise Success with Xamarin and IBM

We recently announced our collaboration with IBM, allowing businesses to build fully native iOS, Android and Windows Phone applications with shared code – while also leveraging IBM Mobile First Worklight’s robust integration, security and connectivity. With this partnership, enterprises are able to deliver both the UI quality consumers demand and the enterprise-grade backend and reliability that corporations require.

IBM and Xamarin Logos

Join IBM and Xamarin technical executives on Thursday, December 11 at 8 am PST/ 11 am EST/ 5 pm GMT for a live webinar as they discuss the IBM and Xamarin partnership, demo the IBM MobileFirst SDK for Xamarin, walkthrough the IBM Worklight platform and answer any developer questions.

Ken ParmeleeKen Parmelee
IBM Business Development Executive & Program Director, MobileFirst

Dustin AmrheinDustin Amrhein
IBM Mobile Technical Leader, MobileFirst


Steve HallSteve Hall
Xamarin Director of Enterprise Mobility


We’ll send a recording after the webinar, so we encourage you to register even if you’re unable to attend.

Register Now


November 18

Getting Started with the Xamarin Android Player

Slow emulators and fragmentation xamarin-android-playerare two of the main frustrations for Android developers. Android emulators are slow to boot and perform poorly, but buying multiple devices to debug an application for multiple API levels isn’t an affordable (or scalable) solution. Neither of these scenarios are ideal for real world mobile development.

At Xamarin, our customers told us they were struggling with slow emulators, so we developed the Xamarin Android Player, introduced at Xamarin Evolve 2014. It can be downloaded from its dedicated page.

Blazing Fast Emulator

Xamarin Android Player Pic 2The Xamarin Android Player runs Android x86 virtual machines using hardware accelerated virtualization technology and is available on both Windows and Mac OS X. It supports OpenGL, delivering smooth, fast graphics. With these features, and a boot time of as little 17 seconds, it’s a blazing fast Android emulator. It also tightly integrates with Visual Studio and Xamarin Studio, so that developers can build, deploy, and debug their apps right from their favorite IDE. Additionally, you can run the Xamarin Android Player side-by-side with the Windows Phone Hyper-V emulator without any conflicts for a great development experience on Windows.

Getting Started

After installing Xamarin Android Player you will be able to browse from a selection of Android images featuring different API levels. Once you have an image installed, you are able to start the player directly from Visual Studio or from Xamarin Studio’s debug on device option.

Xamarin Android Player Images

Even More Features

The Android Player can also emulate different properties of devices, including battery percentage, volume levels, GPS location, and screen orientation. This allows you to try your application in different scenarios. You can even take a screenshot of your running application.
Xamarin Android Player - Pic 3

Download Now

The Xamarin Android player is available to all Xamarin users with an active Xamarin.Android trial or full Xamarin subscription, and the Xamarin Android Player documentation and release notes are great places to help you get started with it today!

7DFPS 2014

Last week saw game developers across the globe coming together to take part in the 3rd annual 7DFPS (7 Day First Person Shooter) game jam. It’s always been a favorite jam of mine, since the 7 day constraint allows for enough development time to really polish an idea beyond the standard 48 hour limitation. The resulting games can serve as excellent prototypes or proofs of concept to develop further.

The other cool thing about the jam is that developers have gone on to build upon 7DFPS prototype successes, like the French team 5 bit games behind DeadCore  or the folks behind SUPERHOT.

This year there have been yet more amazing entries and I’ve picked out a few here that I really enjoyed. As always, I would highly recommend that you visit the 7DFPS site to check out the full listings. It’s also worth noting that not all the Unity projects are tagged as such, so a little exploring is required.

The first game that really caught my eye was Frail Shells by @fromsmiling which creates a fantastic intense atmosphere and goes on to deliver much more than that(be sure to complete that first mission).

Frail Shells755

The next game that impressed me was Shift by @shawnbecktp. I really dug the clean art style, use of motion blur and tight controls.

Shift755

Last, but not least, I really liked Ocean Highway Patrol. Although it’s unfinished, I really liked the core concept and wild art style.

OceanHighwayPatrol755

Naturally this is only a small glimpse of some of the amazing concepts put together over the course of the jam, so I’d highly recommend you go and check out all the awesome things that have been created. Congratulations to all who took part!

November 15

mono-project.com Linux packages – an update

It’s been pointed out to me that many people aren’t aware of the current status of Linux packages on mono-project.com, so I’m here’s a summary:

Stable packages

Mono 3.10.0, MonoDevelop 5.5.0.227, NuGet 2.8.1 and F# 3.1.1.26 packages are available. Plus related bits. MonoDevelop on Linux does not currently include the F# addin (there are a lot of pieces to get in place for this to work).

These are built for x86-64 CentOS 7, and should be compatible with RHEL 7, openSUSE 12.3, and derivatives. I haven’t set up a SUSE 1-click install file yet, but I’ll do it next week if someone reminds me.

They are also built for Debian 7 – on i386, x86-64, and IBM zSeries processors. The same packages ought to work on Ubuntu 12.04 and above, and any derivatives of Debian or Ubuntu. Due to ABI changes, you need to add a second compatibility extension repository for Ubuntu 12.04 or 12.10 to get anything to work, and a different compatibility extension repository for Debian derivatives with Apache 2.4 if you want the mod-mono ASP.NET Apache module (Debian 8+, Ubuntu 13.10+, and derivatives, will need this).

MonoDevelop 5.5 on Ubuntu 14.04

MonoDevelop 5.5 on Ubuntu 14.04

In general, see the install guide to get these going.

Docker

You may have seen Microsoft recently posting a guide to using ASP.NET 5 on Docker. Close inspection would show that this Docker image is based on our shiny new Xamarin Mono docker image, which is based on Debian 7.The full details are on Docker Hub, but the short version is “docker pull mono:latest” gets you an image with the very latest Mono.

directhex@desire:~$ docker pull mono:latest
Pulling repository mono
9da8fc8d2ff5: Download complete 
511136ea3c5a: Download complete 
f10807909bc5: Download complete 
f6fab3b798be: Download complete 
3c43ebb7883b: Download complete 
7a1f8e485667: Download complete 
a342319da8ea: Download complete 
3774d7ea06a6: Download complete 
directhex@desire:~$ docker run -i -t mono:latest mono --version 
Mono JIT compiler version 3.10.0 (tarball Wed Nov  5 12:50:04 UTC 2014)
Copyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com
	TLS:           __thread
	SIGSEGV:       altstack
	Notifications: epoll
	Architecture:  amd64
	Disabled:      none
	Misc:          softdebug 
	LLVM:          supported, not enabled.
	GC:            sgen

The Dockerfiles are on GitHub.

November 13

Transitioning to Infinity

I remember clearly when I sat down at I/O this year, watching the introduction of Material design in the keynote unfold and how, at the time, I told myself there was no way we could implement all of this in Android.

One such aspect that I was highly skeptical of until very recently was the concept of animated transition.

We actually talked about this during our Material Design Evolve session with James and at the time of that talk, the only facility we had been given to do it was by keyframe animations which is incredibly clunky to maintain.

Meet our new private implementation friend, PathDataEvaluator.

This evaluator is able to understand the path definition used by vector drawable and create intermediary versions of it.

This means that given two specific path of a vector drawable, we can use an object animator to, not only animate transformation or style like we have seen before, but also the actual pathData of the vector itself.

Now before you get too excited, it’s not a miracle evaluator. There are two very strong requirements for it to work properly:

  • The path command list needs to be of the same size
  • Each command in that list needs to be of the same type

Basically, the evaluator treats the path data as an array of float extracted from each command parameters and use that to interpolate inbetweeners.

This essentially mean that when crafting your paths, you may need to get a bit creative in the amount of nodes you use in order to make those requirements fit.

As an example, this is what we are going to make:

Intuitively, based on our previously mentioned requirements, we can see there is already fundamental problem when we think of alternating between a standard play icon and a standard pause icon: they don’t have the same amounts of subparts (2 rectangles for pause, 1 triangle for play).

In addition, the pause icon rectangles necessitate 4 control points for each subpart whereas the triangle of the play icon only requires 3.

That’s where the tweaking part comes in, following are how I created those shapes in my editor to solve both issues (nodes handles are highlighted):

The work was actually focused on the play icon by first separating the triangle shape in two right sub-triangles and then adding a (normally unnecessary) extra node onto its hypotenuse.

Each node is also numbered as the order in which the path is drawn has an impact on the look and feel of the animation. With those numbers, you can visualize in your head how the nodes are going to move across the canvas to alternate between the two shapes.

Without further ado, here are the vector drawables we are using:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!-- In your strings.xml file -->
<resources>
	<string name="pause_vector_path">M12,10L20,10L20,38L12,38ZM28,10L36,10L36,38L28,38Z</string>
	<string name="play_vector_path">M16,24L38,24L27.3,30.8L16,38ZM16,10L27.3,17.2L38,24L16,24Z</string>
</resources>

<!-- Resources\drawable\ic_play.xml -->
<vector xmlns:android="http://schemas.android.com/apk/res/android"
	android:height="48dp"
	android:width="48dp"
	android:viewportHeight="48"
	android:viewportWidth="48">
	<group>
		<path android:name="d"
			android:fillColor="@color/white_primary"
			android:pathData="@string/play_vector_path" />
	</group>
</vector>

<!-- Resources\drawable\ic_play.xml is identical except
     replace pathData with the second string resource -->

The path data themselves are stored as a string resources. This makes it easier to use them in different places without having to copy and paste the entire thing.

Notice also how my commands are ordered (M stands for moveto and L for lineto) to reflect what the editor diagram showed and also how each command type maps to the same command type between the two definitions.

Since we want to create a transition we need a container for this that handle state using the Android standard state tracking mechanism. This type of container is called a state-list and, as we already covered in the Evolve video above, we now also have an equivalent version that supports animated transition between state: AnimatedStateListDrawable.

Here is my definition for the play/pause button state (based on the state_checked presence):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<animated-selector xmlns:android="http://schemas.android.com/apk/res/android"
    android:constantSize="true">
    <item
        android:drawable="@drawable/ic_pause"
        android:state_checked="true"
        android:id="@+id/pause_state" />
    <item
        android:drawable="@drawable/ic_play"
        android:id="@+id/play_state" />
	<transition android:fromId="@id/play_state" android:toId="@id/pause_state" android:reversible="true">
		<animated-vector android:drawable="@drawable/ic_play">
			<target android:name="d" android:animation="@anim/play_pause" />
		</animated-vector>
	</transition>
</animated-selector>

You can watch the Evolve video again for a longer explaination of how this works but essentially we are now naming our various <item /> elements with an id so that we can reference them for animation in <transition /> blocks.

Inside the transition, you’ll find our known companion AnimatedVectorDrawable referencing this object animator definition:

1
2
3
4
5
6
7
<!-- Resource\anim\play_pause.xml -->
<objectAnimator xmlns:android="http://schemas.android.com/apk/res/android"
	android:duration="250"
	android:propertyName="pathData"
	android:valueFrom="@string/play_vector_path"
	android:valueTo="@string/pause_vector_path"
	android:valueType="pathType" />

Key aspect is the valueType attribute that is set to pathType (the only actual way to can reference the non-public PathDataEvaluator class) and the property name set to pathData to change the corresponding member in the vector drawable. For the rest, you can tweak this like any other animator.

Last piece is to show this transition in something. The default Android framework offers a CheckedTextView for those cases but no CheckedImageButton (because using Checkbox can in some occasions result int a bit of pain with positioning). It’s easy to implement though:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public class CheckedImageButton : ImageButton, ICheckable
{
	static readonly int[] CheckedStateSet = {
		Android.Resource.Attribute.StateChecked
	};
	bool chked;

	// Add standard constructors

	public override bool PerformClick ()
	{
		Toggle ();
		return base.PerformClick ();
	}

	public void Toggle ()
	{
		Checked = !Checked;
	}

	public bool Checked {
		get {
			return chked;
		}
		set {
			chked = value;
			RefreshDrawableState ();
			Invalidate ();
		}
	}

	public override int[] OnCreateDrawableState (int extraSpace)
	{
		var drawableState = base.OnCreateDrawableState (extraSpace + 1);
		if (Checked)
			MergeDrawableStates (drawableState, CheckedStateSet);
		return drawableState;
	}
}

You can use this class and simply set the android:src attribute to the animated state-list drawable.

Also don’t forget to set the android:background of the button to use the theme value ?android:selectableItemBackgroundBorderless to get the nice ripple effect on touch.

To conclude, you can still use the keyframe approach when doing animated state-list transition if you actually want to invest the time crafting each intermediary state maybe because it does a complex movement that can’t be naively interpolated.

But if you don’t need to, we now have an easy, fast and cumberless way to create beautiful state transitions using vector drawables.

Monologue

Monologue is a window into the world, work, and lives of the community members and developers that make up the Mono Project, which is a free cross-platform development environment used primarily on Linux.

If you would rather follow Monologue using a newsreader, we provide the following feed:

RSS 2.0 Feed

Monologue is powered by Mono and the Monologue software.

Bloggers