There are several ways to extend Xamarin.Forms to finely tune your apps’ user interfaces, including the use of custom renderers and, more recently, effects. Sometimes, though, you just want to take a native control and place it directly into your Xamarin.Forms application without any of the ceremony and code around these two other approaches. This is where the newly announced Native Embedding (Xamarin.Forms 2.2.0+) feature comes in, enabling you to easily add a native control to any Xamarin.Forms layout.

Native Embedding

Set Up

It’s easier and recommended to use Shared Projects for native embedding, since the feature is exposed as platform extension methods on a Xamarin.Forms layout control, but it can also be accomplished by exposing the layout in a portable class library. Since we’ll use a shared project, we can use conditional compilation for each platform we wish to add the native control to. For this blog we’ll take a look at how to embed an Android and iOS control onto a Xamarin.Forms app that has a ListView on it.

Currently, the code is a simple ListView inside of an AbsoluteLayout:

Android Floating Action Button

At Xamarin Evolve Jérémie and I gave a talk on Material Design for Android applications where Jérémie showed off an amazing vector drawable animation in a FAB. Let’s leverage the hard work Jérémie did for his traditional Android app and bring it over to a Xamarin.Forms application. To get this working, we’ll copy over Jérémie’s CheckedFab code and resources from his Buzzeroid application.

At the top of this page we’ll bring in a few Android specific namespaces

To add the native FAB all we need to do is create it with the Xamarin.Forms context and set a few properties and events:

Now we can run the application and see our FAB working with full animations!

FAB Embedding

iOS Native Controls

So far, we’ve spiced up the Android page with a control that only exists on Android platforms, and the same can be done for iOS with a segmented control that is used to filter content in the list. This time, instead of adding Android namespaces to the top of the page, we’ll add iOS specific namespaces:

Then simply create the iOS control and insert it into the top of the StackLayout:

NativeTest

Start Embedding Controls

There you have it! With just a few lines of code in our shared project, we’ve embedded two completely different controls in our iOS and Android projects. Building your app in XAML and portable class libraries? Check out the next evolution of native embedding with the next series in this blog post.

This is just the beginning, as native embedding opens up a world of possibilities. Be sure to read through our entire native embedding documentation for more great examples and download this sample from my GitHub page.