Before starting talking about renderers, let's answer one important question first. What Is a native control?
Native controls are what presents UI in any application and, each platform (iOS,Android, UWP) has its own selection of unique native controls.
Xamarin.Forms exposes a common set of controls across all platforms. And by common we mean not every native control (Button, Checkbox,Switch,etc) has a Xamarin.Forms version. Xamarin.Forms supports native controls embedding in this cases, but how it works?
Xamarin.Forms containers holds derived types from Xamarin.Forms.View, so a conversion is needed from native type to View as shown below (iOS.UIButton to Xamarin.Forms.View). Xamarin.Forms already provides us with some extension methods we can use to perform this conversion as we will see next.
- Adding Native Controls to Xamarin.Forms Layout
In this example we will add an Android Native FloatingActionButton to our Forms layout. So lets create a new Xamarin.Forms called Renderers project and for this example we are going to use a Portable Class Library (PCL).
1.-In our PCL project lets add a new Interface. This will contain only one method we will use later to get FloatingActionButton from Android project.
2.-Next, we need to write the implementation for previous method in Android project, so lets add a new class called FloatingActionButtonFactory.cs which will implement IFloatingActionButtonFactory.
In MainActivity.cs we need to create a new static field and initialize it:
3.- In Our PCL project now we need to use the method we just created in our Native Android Project from Xamarin.Forms. Open MainPage.xaml and lets add just one Grid called mainStack.
4.- Open MainPage.xaml.cs and add following to use our FloatingActionButtonFactory
Compile everything and test it on the emulator and you will see FloatingButton being rendered correctly:
comments powered by Disqus