February 11, 2015

Behaviors in Xamarin.Forms

By

Last month, we announced some exciting new features in Xamarin.Forms as part of the 1.3 release. One of these features is Behaviors, which are extremely useful for attaching a piece of functionality to an existing element in a view. Technically, they are C# classes that inherit from Behavior<T> where T is the UI element to which a functionality is attached. Behaviors are powerful because they are reusable and easy to incorporate into unit testing since they are an independent piece of functionality. They can be used from the simplest example, like adding an email text validator to the Entry element, to advanced situations like creating a rating control using tap gesture recognizer in a view. Let’s take a look at how to get started with behaviors.

Behaviors

A behavior class must inherit from Behavior<T> and override two methods OnAttachedTo(T view) and OnDetachingFrom(T view).

{
    protected override void OnAttachedTo (Entry bindable)
    {
		...
    }
    protected override void OnDetachingFrom (Entry bindable)
    {
		...
    }
}
  • OnAttachedTo – This method is fired immediately after the behavior is attached to the view. You can use this method to add a specific functionality to the UI element. For example, you can subscribe to the TextChanged event of the Entry control and validate the text for email.
  • OnDetachingFrom – This method is fired when the behavior is removed from the attached control. You can use this method to remove the TextChanged event handlers that were previously attached to avoid memory leaks.

XAML

Every VisualElement has a behavior collection. Behaviors are attached to the element by simply adding the behavior to that collection.

<Entry Placeholder="Sample">
  <Entry.Behaviors>
    <local:SampleBehavior  />
  </Entry.Behaviors>
</Entry>

To see this in action, let’s create an email validator behavior and attach it to the Entry element.

Email Validator Behavior

EmailValidator-Xamarin.FormsValidating emails from user keyed text is the most common requirement in an app these days, and this is something that you might need to use more than once. Wouldn’t it be nice to simply add the email validation logic to behaviors and attach them to the Entry element? Not just once, but as many Entry elements as you want?

To achieve this, all you need to do is create a behavior in the OnAttachedTo method by subscribing to the TextChanged event and adding your email validation logic within that. Be sure to unsubscribe the TextChanged handler in the OnDetachingFrom method.

public class EmailValidatorBehavior : Behavior
{
    const string emailRegex = @"^(?("")("".+?(?<!\\)""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))" +
        @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9][\-a-z0-9]{0,22}[a-z0-9]))$";
    static readonly BindablePropertyKey IsValidPropertyKey = BindableProperty.CreateReadOnly("IsValid", typeof(bool), typeof(NumberValidatorBehavior), false);
    public static readonly BindableProperty IsValidProperty = IsValidPropertyKey.BindableProperty;
    public bool IsValid
    {
        get { return (bool)base.GetValue(IsValidProperty); }
        private set { base.SetValue(IsValidPropertyKey, value); }
    }
    protected override void OnAttachedTo(Entry bindable)
    {
        bindable.TextChanged += HandleTextChanged;
    }
    void HandleTextChanged(object sender, TextChangedEventArgs e)
    {
        IsValid = (Regex.IsMatch(e.NewTextValue, emailRegex, RegexOptions.IgnoreCase, TimeSpan.FromMilliseconds(250)));
        ((Entry)sender).TextColor = IsValid ? Color.Default : Color.Red;
    }
    protected override void OnDetachingFrom(Entry bindable)
    {
        bindable.TextChanged -= HandleTextChanged;
    }
}

IsValid – BindableProperty

There are a number of ways you can handle the validation results. For example, you can set the TextColor of the Entry field to red to indicate the invalid email, or you can create an IsValid BindableProperty and let the consuming code decide how the validation needs to be handled.

<Entry Grid.Row="0"
 		Grid.Column="1"
        Placeholder="Email" >
	<Entry.Behaviors>
	  <local:EmailValidatorBehavior x:Name="emailValidator"/>
	</Entry.Behaviors>
</Entry>
<Image Grid.Row="0"
	   Grid.Column="2"
	   x:Name="emailSuccessErrorImage"
	   Style="{Binding Source={x:Reference emailValidator},
	                        Path=IsValid,
	                        Converter={StaticResource boolToStyleImage}}"/>

In the above code, BooleanToObject converter is used, which converts the IsValid boolean value to an appropriate image – a green tick is shown when true and a red error for false.

Adding Multiple Behaviors

AgeValidator-Xamarin.Forms In many instances, you may want to add multiple validators to the UI element. For instance, you might limit the length of an entry field to two characters and restrict the characters to numbers only. You can do this by adding both the behaviors to the same UI element. An example of this would be asking the user to key in his or her age, and restricting the field to numbers limited to two characters. If you notice the code, the MaxLengthValidator accepts the MaxLength property, which gives you the flexibility to reuse this validator for many other occasions.

 <Entry Grid.Row="2"
 		Grid.Column="1"
       	Placeholder="Age">
 	<Entry.Behaviors>
    	<local:NumberValidatorBehavior x:Name="ageValidator" />
    	<local:MaxLengthValidator  MaxLength="2"/>
  </Entry.Behaviors>
</Entry>

Rating Control Using Behaviors

StarBehavior-Xamarin.Forms Behaviors are powerful and can be used to write advanced code, such as creating a star based rating control that uses the tap gesture recognizer. The sample here uses logic to find which star in the group was tapped and sets the IsStarred property of self and the other stars in the group to appropriate values. Since the entire logic of the rating is encapsulated inside a Behavior, you can easily re-arrange the stars in the UI or even change them completely, to smilies for instance. You can download this sample from my GitHub repository.
 
 
 

For even more information on Xamarin.Forms, be sure to check out our samples and the detailed documentation.

Discuss this post in the Xamarin forums

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
February 10, 2015

Webinar Recording: What’s New in Xamarin.Forms 1.3

By

Xamarin.Forms allows developers to easily create cross-platform user interfaces that can be shared across Android, iOS, and Windows Phone. The user interfaces are rendered using the native controls of the target platform, allowing Xamarin.Forms applications to retain the appropriate look and feel on each platform.

The Xamarin.Forms 1.3 release included many enhancements and fixes. In the webinar below, I provide an overview of these new features, including Styles, Triggers, Behaviors, Application Lifecycle, and much more.

Additional Resources

Check out our updated docs for info on the app lifecycle, styles, and fonts.

The code is on GitHub including the behaviors and triggers samples. The slides are also available.

Q&A

So if I create a new Xamarin forms solution will I get the Windows Phone app created also in 1.3? Is this the same in Visual Studio?

Everything that you saw here is the same in Visual Studio. The key difference is when you create a new Xamarin.Forms solution in Visual Studio you also get the Windows Phone project setup for you. Xamarin Studio only creates apps for iOS and Android.

Are styles currently only “explicit”, as opposed to implicit if a key is omitted?

No, an implicit style is created when no key is supplied in the style definition. The implicit style will automatically be applied to all controls of the TargetType within the scope of the style (for example the entire application if added to the App’s resource dictionary, or just to an individual ContentPage or other VisualElement if the style is added there).

If a key is supplied in the style definition, the style must be explicitly applied to particular controls.

Can I apply two styles to one element?

Not directly, but a style can inherit from another style, which could then be applied. The working with styles example shows how to use the BaseResourceKey to inherit from an existing style. You can also use BasedOn to specify a style object to inherit.

Using this approach you can also inherit from the built-in Device.Styles to override certain properties (eg. color).

Using DataTriggers, can a single button be influenced by multiple entry controls (for example validating username and password before enabling a login button)?

Yes, this is exposed via MultiTrigger functionality.

Is there XAML Intellisense support in Visual Studio?

Xamarin Studio has had Intellisense support for some time now, in Visual Studio you are able to download and install the Mobile Essentials pack (also Resharper 9 has added support).

Is there an example of using ResourceDictionary from code behind rather than XAML?

The working with styles example includes a (commented out) C# code behind example of working with the application’s ResourceDictionary.

Discuss this blog post in the Xamarin Forums

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
February 6, 2015

Show Us Your App Contest Winners!

By

Our latest contest asked our community to show us all of the beautiful apps that you have been working hard to build! There were a lot of really great submissions and it was very difficult to narrow it down, but a few clearly stood out.

So, without further adieu, the winner for the best Xamarin app video and $100 store promotion credit goes to…

Djubble!

The fun, fast and easy way to get your friends together and some have fun! You can create a Djubble in less than a minute and get answers in less than a second. All your friends need to do is swipe!



And the winner for the best Xamarin app concept and $100 store promotion credit goes to…

QuickPlan!

The easy to use project planning app, with strong communication, synchronisation and integration supports. Simplify the creation of organizational charts by designing in tree structure!


A big thanks to everyone who participated in the Show Us Your App Video Contest. It’s wonderful to see all of the creative ideas this community is able to bring to life when developing with Xamarin. Didn’t manage to get an entry submitted this time? No worries! Keep an eye on the Xamarin Blog for our next contest announcement.

Want to see more awesome? Visit our Show Us Your Apps forums thread for even more amazing apps built with Xamarin!

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
February 5, 2015

300 Components and Counting

By

Add some awesome to your app with a component from the Component Store!Since launching in early 2013, the Xamarin Component Store has been a big hit, and today we are happy to announce that we have over 300 components ready to integrate into your apps from directly within Xamarin Studio or Visual Studio.

Tons of Functionality

The community has been hard at work building incredibly useful components, complete with high-quality documentation and samples designed to make app development with Xamarin a snap. Each day, amazing partners like Microsoft, Couchbase, Salesforce, and SAP come onboard to make adding functionality from their solutions into your native mobile apps as easy as possible.

Emerging Devices

Google GlassWe’ve also extended Xamarin’s C# story to many emerging platforms, including Google Glass, Monkey.Robotics, Google Cast, Amazon Fire TV, and Fire OS.

Plugins for Xamarin

plugin_icon_nugetWe are pleased to introduce a new section to the Component Store, Plugins, a special kind of NuGet that adds cross-platform functionality or abstracts platform specific functionality to a common API. There you will find our most popular cross-platform plugins, such as Settings, Vibrate, Geolocator, and more. In addition, you will find a hand curated list of plugins on the Plugins for Xamarin GitHub page.

Unified API Support

In addition to all of these great new components, we also wanted to give you an update on existing components and Unified API support for iOS. We have worked closely with our amazing Xamarin Component developer community to update the vast majority of our iOS components to support our new Unified API, and are actively working with all of our component publishers to reach 100% coverage in the near future.

Build and Submit Components

It has never been a better time to build and submit your very own library to the Xamarin Component Store. The Component Store is a great way to promote the hard work that you have put into your libraries and supply developers with a great experience getting started. Be sure to read our full component store submission documentation on how get started. If you already have a NuGet package be sure to read through our brand new Component + NuGet packaging documentation, which now allows you bundle your NuGet and dependencies directly into your Component.

Get Started Using Components

With the help of the Component Store, you can have a gorgeous, functional app in minutes. From user interface and design to the backend services that power your app, the Component Store has it all. If you’re not sure where to get started, we’ve made it even faster to start building with components by including start up guides and working samples reviewed by Xamarin’s Components Team. Head over to the Components Store today to get started!

Discuss this blog post in the Xamarin Forums

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
February 4, 2015

Join Xamarin at IBM InterConnect 2015

By

interconnect-badge-160x160_join_usTo celebrate our Xamarin and IBM MobileFirst global partnership, we’re going big for IBM’s InterConnect developer conference. We’ll showcase how Xamarin and IBM MobileFirst give you the tools to build high-quality, high performance native mobile apps that seamlessly integrate with enterprise systems. With Xamarin and IBM, you give your users the best of both worlds.

We’re looking forward to a successful, informative event — and invite you to join us for the show. Mark your calendars and see you in Las Vegas, February 23-26!

Sessions

IBM MobileFirst Mobile Apps with Bluemix in C# for iOS and Android Using Xamarin Studio

Mohan SabojiJoin Mohan Saboji, IBM MobileFirst Development Manager and Steve Hall, Director of Enterprise Mobility, Xamarin, for their hands-on lab. The IBM MobileFirst SDK for Xamarin gives you the tools you need to create the experience your users demand, with the security and integration your enterprise requires. They’ll dive into Xamarin Studio and demonstrate the power of C# to power native, connected apps for iOS and Android.

Monday, February 23
10:30 AM – 12:30 PM
Mandalay Bay, South Seas Ballroom

Register

Prepare for Enterprise Mobile Success: Xamarin and the IBM MobileFirst Platform Foundation

Steve HallDon’t miss Steve Hall, Xamarin’s Director of Enterprise Mobility, at his SpeedGeek station, where he’ll give ten minute lightning Xamarin and IBM MobileFirst demonstrations. From there, he’ll answer your questions and make sure you’re ready to go mobile with the IBM MobileFirst SDK for Xamarin.

Tuesday, February 24
12:00 PM – 2:00 PM
5:00 PM – 6:00 PM
dev@InterConnect, MGM Grand, 3rd Floor (Developer Playground)

Events

Xamarin – IBM @ InterConnect Happy Hour

Kick back and relax with Xamarin and IBM. Stop by, meet Xamarin and IBM executives and show us, and your like-minded peers, what you’ve been working on and what you’d like to develop.

Monday, February 23
5:30 PM – 7:00 PM
Mandalay Bay (suite to be announced)

RSVP

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
February 3, 2015

Announcing the Xamarin.Forms Book Second Preview Edition!

By

Creating-Mobile-Apps-with-Xamarin-FormsSince Xamarin Evolve 2014, we’ve received fantastic feedback on the first Preview Edition of Charles Petzold’s Creating Mobile Apps with Xamarin.Forms, so we’re excited to announce that we’re making a Second Preview available for download.

The book has been updated to incorporate feedback from the first preview, as well as to include the latest features from Xamarin.Forms 1.3. Readers will notice a substantial re-organization of the book and additional XAML content that was not in the first preview.

The following chapters are available for download today:

Chapter 1. How Does Xamarin.Forms Fit In?

Chapter 2. Anatomy of an App

Chapter 3. Deeper into Text

Chapter 4. Scrolling the Stack

Chapter 5. Dealing with Sizes

Chapter 6. Button Clicks

Chapter 7. XAML vs. Code

Chapter 8. Code and XAML in Harmony

And there are many more chapters still to come! We will be updating the download page every week or so with a new chapter until the book is complete and we move into the final editing and publishing phase.

We hope you enjoy the second preview chapters as they become available. For more Xamarin.Forms content, check out the Developer Center.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
February 2, 2015

Xamarin.Forms Video: Understanding the Basics

By

It’s 2015. If it hasn’t happened already, it’s likely you’ll be asked to build a mobile app, or at the very least build an app that can integrate with mobile platforms. Notice that I said “platforms”, not “platform”.  To reach all of your customers and support BYOD work practices, your app will have to run on iOS, Android, and Windows Phone.

This scenario is a perfect fit for Xamarin.Forms, which lets you create fast, native apps with re-usable UI code. With Xamarin.Forms, we’ve seen code-reuse go from 70% to over 90%, enabling developers to share the same business and back-end code, as well as user interfaces that can be written in C# or XAML.

Forms makes this happen by expressing layout in its control set language for layouts and widgets like text boxes and buttons. When you deploy your app to each platform, it renders those visual elements into native UI elements, creating a responsive app that your users can intuitively use.

Craig Dunn (who writes much of our documentation) and I recorded this video to show off the basic capabilities of Xamarin.Forms running on iOS, Android, and Windows Phone. Watch it in full-screen to see Craig step through the code and run it on real, physical devices:

If you need to access native device functionality like GPS, Text-To-Speech, or phone dialing, Xamarin.Forms gives you that capability with the Dependency Service or Custom Renderers. This blog post shows you how.

 

Learn More & Get Started

To see Xamarin.Forms for yourself, visit our website and read more in our developer documentation. Live instruction is also available from Xamarin University.

You also can download the code in the video, including many other Xamarin.Forms samples from Github.

To see an app built on Xamarin.Forms, check out our recently released demo, VervetaCRM.

VervetaDashboard

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
January 30, 2015

Fall in Love with Xamarin Events Around the World!

By

This month, let Cupid’s arrow lead you right to a Xamarin event near you! Stay in tune by following @XamarinEvents posts on Twitter and be sure to check out our Events forum with new events being added daily from all around the world!

meetup-banner

Here are some of the upcoming Xamarin developer group meetups:

Seattle Mobile .NET Developers Group us

  • Seattle, WA: Tuesday, Feb 3rd 6:00PM
  • Developing for Android Wear, welcome to the wrist world

Barcelona Mobile .NET Developers Group __

  • Barcelona, Spain: Thursday, Feb 5th 7:00PM
  • Go Mobile with C# and Xamarin

Chicago .NET Developers us

  • Chicago, IL: Tuesday, Feb 5th 6:00PM
  • Diving in Xamarin.Forms 1.3

XHackers __

  • Bangalore, India: Saturday, Feb 7th 9:00AM
  • XHackNight – two day cross platform hackathon

Kansas City Mobile .NET Developers Group us

  • Kansas City, MO: Tuesday, Feb 10th 6:00PM
  • Xamarin Forms: Writing one app to rule all your platforms

Xamarin User Group Frankfurt __

  • Frankfurt, Germany: Tuesday, Feb 10th 6:00PM
  • First Meetup!

Sydney Mobile .NET Developers __

  • Sydney, Australia: Tuesday, Feb 10th 6:30PM
  • A slimmer, leaner, faster app using the new Graphic class!

Gauteng Xamarin User Group __

  • Johannesburg­,South Africa: Tuesday, Feb 10th 6:30PM
  • First Meeting for JHB Xamarin User Group

Birmingham Xamarin Mobile Cross Platform User Group __

  • Birmingham,United Kingdom: Wednesday, Feb 11th 6:30PM
  • What’s new from Xamarin Evolve 2014

DFW Mobile .NET us

  • Irving, TX: Wednesday, Feb 11th 6:00PM
  • Three-Way Data Binding in Universal Apps: View, View Model, and Cloud

Northern Virginia Mobile C# Developers’ Group us

  • Mc Lean, VA: Wednesday, Feb 11th 7:00PM
  • Building Mobile Apps using Azure Mobile Services – Fabian Williams

London Mobile Developers (.Net / Xamarin) __

  • London,United Kingdom: Thursday, Feb 12th 7:00PM
  • 1- Wearables and Xamarin / 2 – Ionic / 3 – contest

Houston Xamarin C# Mobile Developers Group us

  • Houston, TX: Wednesday, Feb 18th 6:30PM
  • PushSharp

NYC Mobile .NET Developers Group us

  • New York, NY: Wednesday, Feb 25th 6:30PM
  • Building Context-Aware Apps with iBeacons

Copenhagen Xamarin Developers us

  • Copenhagen, Denmark: Thursday, Feb 26th 5:00PM
  • MVVM Talk

XL Soft us

  • Tokyo, Japan [日本]: Friday, Feb 27th 2:00pm
  • Cross Platform Mobile Development Seminar by Microsoft Japan

Didn’t see your city listed above? Not to worry, look to this February Announcements forum for even MORE upcoming Xamarin events, meetups, and presentations happening every day!

Want a developer group in your area and are interested in getting one started? We are here to help! Here’s a tips and tricks guide on staring a developer group, a brand new introduction to Xamarin slide deck, and of course our community sponsorship program to get you on your way. Also, we love to hear from you so please feel free to send us an email or tweet @XamarinHQ to help spread the word and continue to grow the Xamarin community.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone

Video: Brett Favre-Backed Sports App Scores Big with Xamarin

By

Sqor Sports LogoWe’re excited to share Sqor’s Xamarin story with you today, including a special message from Sqor investor and board member, legendary football quarterback Brett Favre.

Sqor Sports, a San Francisco-based startup, is a unique social network that is taking on Twitter, Facebook and Instagram as the best social platform for fans to engage directly with their favorite professional athletes. They are also disrupting how sports economics work by enabling athletes to monetize outside of the league—in some cases paying them to create content, providing sponsorship opportunities for businesses and by enabling athletes to crowdfund for their charities or, in the case of Olympic athletes, support to pursue their dreams.

The Sqor team chose to go all in with Xamarin from the beginning, building their iOS and Android apps with the Xamarin Platform, testing them with Xamarin Test Cloud, and monitoring the apps in the wild with Xamarin Insights. Going up against the giants of social media to build their user base, the Sqor team relies on Xamarin’s end-to-end solution to maintain a top-quality user experience for both the athletes creating content and for the fans consuming it.

Watch the video to see Xamarin and Sqor in action.

To start following top athletes, from the football players preparing for this Sunday’s Super Bowl XLIX to your favorite synchronized swimmer, visit Sqor Sports and sign up for a free account today.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone
January 28, 2015

Android Tips: Hello Material Design v7 AppCompat

By

Nexus 4 (KitKat) Screentshot 2Android 5.0 Lollipop introduced a complete refresh, known as Material Design, to the Android user interface, which generated rapid adoption throughout the development community. Until Google introduced revision 21 of the Android Support v7 AppCompat library, Material Design themes, controls, and features were utilized only if you wanted to target devices running API 21.

We recently took a look at how this library gives developers an opportunity to add the ActionBar to applications targeting older devices all the way back to API 7. However, now you can use this updated library to add Material Design to any of your applications and use new controls like the new Toolbar, which replaces the ActionBar. Let’s see how easy it is to get started with the new Support Library v7 AppCompat by updating our Toolbar example.

Getting Started

To start integrating AppCompat into your Android project you will want to install the Support Library v7 AppCompat from the Component Store or directly from NuGet. This will also install the Support v4 Library, which is required because it provides controls that help maintain backwards compatibility.

Supportv7Component

Since you will now be able to target older versions of Android, you will want to adjust your Minimum and Target Android version under Android Application in the project options.

MinandTarget

Updating to Material Theme

There are many differences to the actual resources that are embedded into your app when you use the AppCompat library. This means that the actual themes and attributes are completely different between normal Material and AppCompat themes. You will find three new themes that you can inherit from:

Dark: Theme.AppCompat
Light: Theme.AppCompat.Light
Light with Dark ActionBar: Theme.AppCompat.Light.DarkActionBar

MaterialDesign

StylesFoldersTo use one of these themes, you’ll want to create two folders under your Resources folder named values and values-v21 where you will create a styles.xml where you can customize your applications theme. In our values/styles.xml you will create the base theme of your application and then set custom attributes. You will see that these attributes are different than using the standard Material Theme since they have dropped the android: prefix as they are now part of your application.

values/styles.xml

<resources>
  <style name="MyTheme" parent="MyTheme.Base">
  </style>
  <!-- Base theme applied no matter what API -->
  <style name="MyTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:windowNoTitle">true</item>
    <!--We will be using the toolbar so no need to show ActionBar-->
    <item name="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="colorPrimary">#2196F3</item>
    <!-- colorPrimaryDark is used for the status bar -->
    <item name="colorPrimaryDark">#1976D2</item>
    <!-- colorAccent is used as the default value for colorControlActivated
         which is used to tint widgets -->
    <item name="colorAccent">#FF4081</item>
     <!-- You can also set colorControlNormal, colorControlActivated
         colorControlHighlight and colorSwitchThumbNormal. -->
  </style>
</resources>

Then, inside of your values-v21/styles.xml, you’ll set a few more custom attributes that can take advantage of transitions on devices running Lollipop:

<resources>
  <!--
        Base application theme for API 21+. This theme replaces
        MyTheme from resources/values/styles.xml on API 21+ devices.
    -->
  <style name="MyTheme" parent="MyTheme.Base">
    <item name="android:windowContentTransitions">true</item>
    <item name="android:windowAllowEnterTransitionOverlap">true</item>
    <item name="android:windowAllowReturnTransitionOverlap">true</item>
    <item name="android:windowSharedElementEnterTransition">@android:transition/move</item>
    <item name="android:windowSharedElementExitTransition">@android:transition/move</item>
  </style>
</resources>

The last step is to open your AndroidManifest.xml under the Properties folder and add reference to your new theme under the application node with android:theme="@style/MyTheme".

Integrate Toolbar

Perviously, we saw how to integrate the new Toolbar into your application. The core of that remains the same, except that you will now directly reference the new Toolbar widget from the Support Library:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    local:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    local:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

Note here the use of custom themes directly for the Toolbar and the use of custom attributes. These are a change form the normal use of the Toolbar when not using AppCompat. With our Toolbar setup we can now integrate it into our layouts by user the include node to place the Toolbar where you want.

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:local="http://schemas.android.com/apk/res-auto"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <include
        android:id="@+id/toolbar"
        layout="@layout/toolbar" />
    <LinearLayout
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/main_content"
        android:layout_below="@id/toolbar">
    </LinearLayout>
</RelativeLayout>

Update that Activity

The core of any Android application are Activities. When you start using AppCompat, you simply need to update your activities inheritance.
From:

public class MainActivity : Activity

To:

public class MainActivity : ActionBarActivity

You can now setup your Activity to set the SupportActionBar with the new Toolbar that you have embedded into your layout. I prefer to use an alias to ensure the correct Toolbar is always referenced:

using Toolbar = Android.Support.V7.Widget.Toolbar;

Then you simply need to find the Toolbar, set it, and access it in your OnCreate:

protected override void OnCreate (Bundle bundle)
{
  base.OnCreate (bundle);
  // Set our view from the "main" layout resource
  SetContentView (Resource.Layout.main);
  var toolbar = FindViewById<Toolbar> (Resource.Id.toolbar);
  //Toolbar will now take on default actionbar characteristics
  SetSupportActionBar (toolbar);
  SupportActionBar.Title = "Hello from Appcompat Toolbar";
  //..
}

There you have it, you can now run your newly Material Themed Android application on devices that aren’t running Lollipop!

Nexus 4 (KitKat) Screentshot 1

Learn More

You can get the full source code for this project in the Support v7 Sample gallery. There you will also find other awesome examples of more Support v7 libraries such as CardView, RecyclerView, and Palette. During Evolve 2014, Jérémie Laval and I gave two talks on Material Design from Concept to Implementation. (Part 1 and Part 2) that are available to watch now.

Discuss this post in the Xamarin forums.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInEmail this to someone