In last part we just discussed how controls are rendered in Xamarin,Forms and how to embed native controls into our layouts by converting native controls to View objects. In this post we will focus on customizing a renderer for an existing control.

So lets start by answering what is a platform renderer. A platform renderer is the code that translates a Xamarin.Forms Visual Element to a platform-specific control and as you can tell from the image below, Xamarin.Forms provides limited APIs to change control appearence and behavior. For going beyond this limitation CUSTOM RENDERERS are used to let us access ALL native properties.




Xamarin.Forms by default provides platform-specific renderers for EVERY visual element as shown below. If you want to know more about it you can find more info here: https://developer.xamarin.com/guides/xamarin-forms/custom-renderer/renderers/. A platform-specific renderer lets us acess properties on the native control that are not reachable through the Xamarin.Forms API (for example adding a custom animation or shadow to a button).





  • CUSTOMIZING A PLATFORM RENDERER

So lets start customizing a LabelRenderer for Android. The intention is to customize a label to execute a custom Scale animation when label is tapped.

1.- First in our PCL project lets add a new class called ClickableLabel which derives from Label:


2.- In the Android project lets add a new file under Resources/drawable/ called fade_in.xml, add the content as shown below and compile project.

3.- In Android project we need to subclass renderer for the new element we just created (ClickableLabelRenderer). Add a new class called ClickableLabelRenderer.cs . This class is where we can do any customization we want before our customized label gets rendered.



4.- Finally in our PCL project, open MainPage.xaml which at this point only contains a Grid called mainStack and lets use our new ClickableLabelRenderer control we created in point 1.


5.- Finally compile everything and test it on Android simulator and wou will see your new label being rendered and triggering a fade animation when tapped.




comments powered by Disqus