Tag Archives: Xamarin Forms

Advanced decorating of Xamarin Forms Slider for Android…

Alright so today I’m gonna take you guys through a journey of decorating a Xamarin Forms Slider control in Android…

Well we all know how basic the default Slider control in Xamarin Forms, but worry not, there are plenty of ways to decorate it with awesome features,specifically for Xamarin Android! 😀

It all started a few weeks back when I was playing around with the Slider control to add  a whole bunch of complex visual features in one of my company apps.

Let’s get started…

Alright, first thing first, we need set up our Custom Slider control first and attach it’s Custom renderer in Android.

So here goes the Custom Slider control subclassing in Xamarin Forms project…

namespace WhateverYourNamespace
{
    public class CustomSlider : Slider
    {

    }
}

 

Next set up the Custom Slider Renderer in your Android project…

[assembly:ExportRenderer(typeof(CustomSlider), typeof(CustomSliderRenderer))]
namespace WhateverYourNamespace.Droid
{
    public class CustomSliderRenderer : SliderRenderer
    {
        protected override void
                 OnElementChanged(ElementChangedEventArgs<Slider> e)
        {
            base.OnElementChanged(e);

            if (e.NewElement != null)
            {
		// All the customization will go here
            }
        }
    }
}

 

How would I consume this in XAML you ask? Just as another ordinary view… 😉

<StackLayout>

	<local:CustomSlider 
	HeightRequest="7" 
	WidthRequest="350" 
	HorizontalOptions="Center"
	Minimum="0" Maximum="100" />

</StackLayout>

 

Now keep in mind all the customization that we are doing later will be done within this custom renderer.

Something to keep in mind is that,

the Xamarin Forms Slider control’s Android run time native counterpart is the SeekBar…

So the more you aware of the SeekBar’s properties, the more customization you could play around with! 😉

Alright let’s start decorating… 😀

Decoration 1 : Change color theme!

Want to change the color theme of your Slider? Here we go…

Let’s see the code.

if (e.NewElement != null)
{
	// progressbar and progressbar background color
	Control.ProgressDrawable.SetColorFilter(
		new PorterDuffColorFilter(
		Xamarin.Forms.Color.FromHex("#ff0066").ToAndroid(),
		PorterDuff.Mode.SrcIn));
}

 

Use the ProgressDrawable Property and set the ColorFilter to it as you wish… 😉 which will set the color theme to your Progress Bar , Progress Thumb, and the background bar…

Decoration 2 : Change only the Slider’s Thumb Color?

How about changing just the Progress Thumb’s color? Yes you may…

Look at that funky looking Progress Thumb! 😉

Code?

if (e.NewElement != null)
{
	// Set Progress bar Thumb color
	Control.Thumb.SetColorFilter(
		Xamarin.Forms.Color.FromHex("#8000ff").ToAndroid(), 
		PorterDuff.Mode.SrcIn);
}

 

Android SeekBar (which is the native handler of Xamarin Forms Slider on Android) has the Thumb property which allows you to customize the appearance of the little thumbnail head of the Slider control as we have used above.

Next! 😀

Decoration 3 : Change progress background Color?

How about changing only the Progress Bar’s background color? As you can see below..

Look at the boring default progress bar’s background color vs the purple background color! 😉 pretty cool!

Here’s how you do it,

if (e.NewElement != null)
{
	//Set Background Progress bar color
	Control.ProgressBackgroundTintList 
           = ColorStateList.ValueOf(
            Xamarin.Forms.Color.FromHex("#8000ff").ToAndroid());
	Control.ProgressBackgroundTintMode
           = PorterDuff.Mode.SrcIn;
}

 

Use the ProgressBackground property to set the TintList and the TintMode! 🙂

TADAA!

Decoration 4 : How about adding a secondary progress indicator?

Now we all have seen secondary progress indicators in progress bars, specially in online video stream players… 🙂 example take the Youtube player! 😉 So have you ever wanted to add such a cool feature to your Xamarin Forms Slider in Android? Let me show you how its done… 😉

Look how cool that is yeah! 😉

Alright let’s get into coding…

Now in Android we have this built in property called SecondayProgress which allows you to set a secondary progress value to your Slider or Seekbar as of native Android handler.

if (e.NewElement != null)
{
	// secondary progress value in Xamarin Forms units
	int secondaryProgressValue = 50;
	
	// secondary progress value in 
	// Android native Seekbar units
	int secondaryProgressValueInAndroidUnits =
	(int)((secondaryProgressValue - 
			((CustomSlider)Element).Minimum) /
	(((CustomSlider)Element).Maximum -  
			 ((CustomSlider)Element).Minimum) * 1000.0);

	// set the secondary progress value
	Control.SecondaryProgress = 
	secondaryProgressValueInAndroidUnits;
}

 

There you go, you can see that we are setting the SecondaryProgress value, but also take a closer look at the calculation that we are doing before setting it.

Now Xamarin Forms Slider and Xamarin Android Seekbar which is the handler for the Slider control, uses different value types or unit types for setting the Progress and the Secondary Progress values in native level. If we want to set the value from Xamarin Forms value units then we need to convert that value to Android Seekbar’s native values which is exactly what we are doing at the calculation. So basically we are setting the Xamarin Forms unit value according to the native units to Seekbar control.

Oh if you want to set the Secondary Progress from Xamarin Forms level then you can easily create a property in the CustomSlider class and use it down here in your Custom Renderer class 🙂 Imagination is the limit! 😉

Decoration 5 : May be change the Color of secondary progress indicator?

How about we spice it up by changing the color a little of the secondary progress? 😉

Look at that!

Time for coding…

Android Seekbar has this property called SecondaryProgressTintList and SecondaryProgressTintMode which allows you to achieve the above results and set the secondary progress color as you wish…

if (e.NewElement != null)
{
	//Set Seconday Progress bar color
	Control.SecondaryProgressTintList = 
	      ColorStateList.ValueOf(
		Xamarin.Forms.Color.FromHex("#8000ff").ToAndroid());
	Control.SecondaryProgressTintMode = 
	      PorterDuff.Mode.SrcIn;

	// secondary progress value in Xamarin Forms units
	int secondaryProgressValue = 50;
	
	// secondary progress value in 
	// Android native Seekbar units
	int secondaryProgressValueInAndroidUnits =
	(int)((secondaryProgressValue - 
	((CustomSlider)Element).Minimum) /
	(((CustomSlider)Element).Maximum - 
	 ((CustomSlider)Element).Minimum) * 1000.0);

	// set the secondary progress value
	Control.SecondaryProgress = 
		secondaryProgressValueInAndroidUnits;
}

 

And hey of course don’t forget to set the SecondaryProgress value while you’re at it!

Decoration 6 : I would call it Funky delight!

Alright, now all that being said, how about blending some of those different colors adding some funky delight-ness to the Slider? 😉

Well what I mean is, let’s try adding different color’s to Thumb, Progress Bar, Progress Bar background and Secondary Progress Bar!

Too much funky? I thought so!

How about these??? 😉

I know, I love playing with colors being a Visual oriented developer! 😀 lol

Your imagination is the limit fellas!

Here’s how you play around with the colors…

if (e.NewElement != null)
{
	// Different colors for ProgressBar components
	// Set Primary Progress bar color
	Control.ProgressTintList = 
		ColorStateList.ValueOf(
		Xamarin.Forms.Color.FromHex("#6200ea").ToAndroid());
	Control.ProgressTintMode 
		= PorterDuff.Mode.SrcIn;

	//Set Seconday Progress bar color
	Control.SecondaryProgressTintList = 
		ColorStateList.ValueOf(
		Xamarin.Forms.Color.FromHex("#b388ff").ToAndroid());
	Control.SecondaryProgressTintMode 
		= PorterDuff.Mode.SrcIn;

	//Set Progress bar Background color
	Control.ProgressBackgroundTintList = 
		ColorStateList.ValueOf(
		Xamarin.Forms.Color.FromHex("#b39ddb").ToAndroid());
	Control.ProgressBackgroundTintMode 
		= PorterDuff.Mode.SrcIn;

	// Set Progress bar Thumb color
	Control.Thumb.SetColorFilter(
		Xamarin.Forms.Color.FromHex("#311b92").ToAndroid(),
		PorterDuff.Mode.SrcIn);
}

 

Decide your flavor of colors and go crazy fellas! 😉

Decoration 7 : Remove Thumb Header may be?

Absolutely, check this out…

It’s pretty simply actually, simply set a Tranparent ColorDrawable to the Thumb property.

if (e.NewElement != null)
{
	// Hide thumb
	Control.SetThumb(
		new ColorDrawable(Color.Transparent));
}

 

Woot!

Decoration 8 : Let’s kick it up a notch!

Let’s add some more vibrant and complex customization to our Slider for Android! 🙂

How about throwing in some cool gradient effects…

So to achieve that, we shall be using Android native Styling with Drawables such as Shape, Gradients and so on.

We will create a native android xml Style file in your Resources/Drawable folder with the name “custom_progressbar_style.xml”

Here’s what you’ll be placing inside of it…

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

  <item android:id="@android:id/background">
    <shape>
      <corners android:radius="15dip" />
      <gradient
       android:startColor="#d9d9d9"
       android:centerColor="#e6e6e6"
       android:endColor="#d9d9d9"
       android:centerY="0.50"
       android:angle="270" />
    </shape>
  </item>
  
  <item android:id="@android:id/secondaryProgress">
    <clip>
      <shape>
        <corners android:radius="15dip" />
        <gradient
             android:startColor="#e6b3e6"
             android:centerColor="#ffcce0"
             android:endColor="#e6b3e6"
             android:centerY="0.50"
             android:angle="270" />
      </shape>
    </clip>
  </item>
  
  <item android:id="@android:id/progress">
    <clip>
      <shape>
        <corners android:radius="15dip" />
        <gradient
         android:startColor="#ff0066"
         android:centerColor="#ff00ff"
         android:centerY="0.50"
         android:endColor="#cc0052"
         android:angle="270" />
      </shape>
    </clip>
  </item>
  
</layer-list>

 

So to explain the above a little bit, we have created a Style layer-list which assigns the given styling items to the specific id’s of the SeekBar native control, such as the background, secondaryprogress, progress as you have noticed. Those drawable objects will replace the default styles of those segments in the SeekBar with these defined drawable objects.

First we are using a Shape drawable to to the Background property, which creates a gradient layer with the given colors and angle for creating a gradient effect! Also we are setting a radius value to corner so that the corners will be curved nicely.

Next for the Progress and the SecondaryProgress properties we are creating a similar Shape gradient as before but we are clipping it according to the given values of each of them.

if (e.NewElement != null)
{
	// Set custom drawable resource
	Control.SetProgressDrawableTiled(
	Resources.GetDrawable(
	Resource.Drawable.custom_progressbar_style,
	(this.Context).Theme));

	// Hide thumb to make it look cool lol
	Control.SetThumb(new ColorDrawable(Color.Transparent));
}

 

There’s how you set it in the custom renderer level, simply call the SetProgressDrawableTiled() method by passing the custom style of what we created above.

Also I have disabled the Thumb, just to make it look cooler. Its up to you though.

If you want to do more extensible customization like above and may be preserve the Thumb view and style that as well? then refer to this stackoverflow article: http://stackoverflow.com/questions/16163215/android-styling-seek-bar

Additionally you could have bitmap images or nine patch images as drawables to styling and so may other stuff.

Now this is like the holy grail.. where as you can see with Android you get full flexibility for any kind of complex customization!

Its only limited by your imagination! 😉

WooT! 😀

Decoration 9 : Can I reduce the above overridden Height?

So you’re worried of the height after setting the custom styling drawables as above? simply reduce the HeightRequest value in your Xamarin Forms code for our custom Slider view.

Right after we set the Custom ProgressDrawable styles in the renderer level, it overrides the Height property of native SeekBar  that’s assigned from Xamarin Forms level for each of those sub-views (ProgressBar, SecondaryProgressBar and Background sub views), so they expands themselves to the fullest as possible with the new Drawable objects.

<local:CustomSlider HeightRequest="7" WidthRequest="350"  HorizontalOptions="Center"
        Minimum="0" Maximum="100" />

 

So the above should give you control over the Height issue!

Or else you could set the dip IntrinsicHeight values in your XML style drawables itself as well (something extra)! 😉

Decoration 9 : Can I  have the above cool-ness programmatically without resources?

So you don’t like to deal with Android Resources and creating the Style XMLs and stuff?

Oh sure, no worries! but you will have to do a little bit of work to get the above simple XML Styling into pure code generated objects!

Let me begin by giving credit to this example written in Java which I found while I was in the same situation: FlatUI/FlatSeekBar.cs

So let’s see how we could create Drawable Style objects in C# code!

Now keep in mind all the Drawable objects we used in our XML file “custom_progressbar_style.xml” has their own programmatical counterparts such as Shape, Gradient and Clip by the names as ShapeDrawable, GradientDrawable, and ClipDrawable and so on likewise.

So we can convert any given XML style to a C# generated style drawable. (any native Android developer should be well aware of this)

So let’s do something similar! 😉

So we are going to create our own Drawable objects and set them to the sub-views of our Slider control for Android, just like how we did with the XML styling, but this time programmatically. Here is how it will look like…

There you haveit, let’s see how we did this…

if (e.NewElement != null)
{
	// Setting drawable styling programatically

	// progress
	var progress = new PaintDrawable(Color.Red);
	progress.SetCornerRadius(
		(int)DpToPixels(this.Context, 10));
	progress.SetIntrinsicHeight(
		(int)DpToPixels(this.Context,10));
	var progressClip = 
		new ClipDrawable(progress, GravityFlags.Left,
		ClipDrawableOrientation.Horizontal);

	// secondary progress
	var secondary = new PaintDrawable(Color.Gray);
	secondary.SetCornerRadius(
		(int)DpToPixels(this.Context, 10));
	secondary.SetIntrinsicHeight(
		(int)DpToPixels(this.Context, 10));
	var secondaryProgressClip = 
		new ClipDrawable(secondary, GravityFlags.Left, 
		ClipDrawableOrientation.Horizontal);

	// background
	PaintDrawable background = new 
                 PaintDrawable(Color.LightGray);
	background.SetCornerRadius(
		(int)DpToPixels(this.Context, 10));
	background.SetIntrinsicHeight(
		(int)DpToPixels(this.Context, 10));

	// retrieve LayerDrawable reference of the SeekBar control
	LayerDrawable layeredDrawableReference 
		= (LayerDrawable)Control.ProgressDrawable;
		
	// apply our custom drawable objects to the 
	// given sub-views through their IDs
	layeredDrawableReference.
	    SetDrawableByLayerId(
		Android.Resource.Id.Background, background);
	layeredDrawableReference.
	    SetDrawableByLayerId(
		Android.Resource.Id.Progress, progressClip);
	layeredDrawableReference.
	    SetDrawableByLayerId(
		Android.Resource.Id.SecondaryProgress, 
                  secondaryProgressClip);
}

 

So basically we are creating our our Drawable objects programatically, in this case PainDrawable objects and giving them different styling values such as Radius, Clipping, IntrinsicHeight and so on.

And then at the end we are going to retrieve the references for the sub-views of our native SeekBar in Android which is the after-rendering counterpart of Xamarin Forms Slider as I mentioned at the beginning. This is going to be a LayerDrawable object, which is going to allow us to set our own custom Drawable objects to each drawable layer by their IDs.

As you can see we are calling the SetDrawableByLayerId() on our LayerDrawable object and passing in the each sub-view reference and custom drawable objects we want to set to them. 😀

Now keep this in mind, here you could have any kind of drawable objects to create your custom drawable styling just like you previously did with GradientDrawable in XML style, have the exact same beautiful visual result rendered programatically! 🙂

That’s it…

Well fellas that’s it for now, well at least that’s all I came across while I was playing around with my Custom Renderer for Xamarin Forms Slider on Android! 😀

Enjoy and share!

CHEERS!

Let’s Override Navigation Bar back button click in Xamarin Forms…

So you would like to override the Navigation Bar back button click event in your Xamarin Forms App? 😉 Yeah could be for a Sign up Page, Order Details Page, or any kind of a Page where you want to do some execution or confirmation before the user actually navigates back to the previous page in your app…

It’s BACKWARD navigation time…

Yes we are not talking about forward navigation here, but BACKWARD navigation! where the user clicks on the back button on the Navigation Bar, or the actual Back button in Android phones, where we need to have some validation before the user actually navigates…

Oh hello! Where do you think you’re going? Are you sure you want to go back?

:\

Do you want to save your changes before you go back?

Please complete the empty fields because you go back!

😮

Do you want to go back before you save your changes?

Please confirm you want to cancel your changes and go back…

😛

Blah blah…

Well you know the scenarios… 😉

ummhh… but in Xamarin Forms?

Yeah the question is can we actually implement this behavior in Xamarin Forms?

YES! you can, but…

well yes obviously you can override the OnBackPressed() method in ContentPage control, but…

it works only on Android and only for the physical back button…

not the Navigation Bar back button…

owwhh SNAP!

Yes fellas, if you want to achieve the above behavior in Xamarin Forms, you literally can not do it straight out of the box, because the override-able  OnBackPressed() method in ContentPage only gets fired on Android’s physical (or screen bottom) back button’s click. It does not work for the Navigation Bar’s back button click.

But I did it…

So here’s a sneak preview of the results of my implementation…

  

Now look at that awesomeness.. When the user clicks on the Navigation Bar’s back button, I’m popping up a confirmation dialog.. 🙂

Alright, how did I do this?

So in order to do this we need to drill down to the native level and handle these Navigation Bar back button click. Let me explain further….

Android

So after compilation the Navigation Bar that we call in Xamarin Forms, turns into the Action Bar for Android during run time. So in order to capture the back button click the Action Bar we need to override the OnOptionsItemSelected() in your MainActivity class, which allows us to capture the navigation bar’s back button click. Since Xamarin Forms runs on a single Activity overriding the above event on your parent Activity class is enough to get our job done. 😉

iOS

And for iOS , the Xamarin Forms’s Navigation Bar is mapped to the UINavigationBar in iOS run time. But unfortunately there’s no way to override the back button click on the default back button in the UINavigationBar, the only solution is to replace the default back button with a custom back button and do our necessary event subscriptions with it. We can replace the default back button with our custom back button at the ViewWillAppear() event call of the UIViewController, and set our custom back button to UILeftBarButtonItem property. 😀

Bridging between Native Xamarin and Xamarin Forms?

Yep just by native implementation is not enough since we need to get a call back to our Xamrin Forms PCL or Shared project level right? So for that we shall be using a simple Action event where we subscribe to in our Xamarin Forms code level, and do the necessary execution when the mentioned Action event gets fired from the native project levels. 😉

Simple as that! 😀

Alright! time for coding.. 😀

So first we need to create a Custom ContentPage to be used as our Page in our Xamarin Forms project, where as we could enable or disable the Nav bar Back button event overriding. And we shall name it as the “CoolContentPage” lol, well why not, it is indeed cool! 😉 lol

namespace WhateverYourNamespace
{
    public class CoolContentPage : ContentPage
    {
        /// <summary>
        /// Gets or Sets the Back button click overriden custom action
        /// </summary>
        public Action CustomBackButtonAction { get; set; }

        public static readonly BindableProperty EnableBackButtonOverrideProperty =
               BindableProperty.Create(
               nameof(EnableBackButtonOverride),
               typeof(bool),
               typeof(CoolContentPage),
               false);
			   
        /// <summary>
        /// Gets or Sets Custom Back button overriding state
        /// </summary>
        public bool EnableBackButtonOverride
        {
            get
            {
                return (bool)GetValue(EnableBackButtonOverrideProperty);
            }
            set
            {
                SetValue(EnableBackButtonOverrideProperty, value);
            }
        }
    }
}

 

So there we have created the Action event that we are going to subscribe to in our Xamarin Forms code level and to be invoked from Xamarin native project level.

You can also see that I’m using a bool property to enable or disable the overriding of the Back Button click event, so that we can decide whether to subscribe to the overriding event or not as a page property.

next Xamarin Android stuff…

So as I explained at the beginning we need to override the OnOptionsItemSelected() event in our MainActivity class in order to capture the nav bar back button click in Android for Xamarin Forms.

public override bool OnOptionsItemSelected(IMenuItem item)
{
	// check if the current item id 
	// is equals to the back button id
	if (item.ItemId == 16908332)
	{
	   // retrieve the current xamarin forms page instance
	   var currentpage = (CoolContentPage)
	   Xamarin.Forms.Application.
	   Current.MainPage.Navigation.
	   NavigationStack.LastOrDefault();

	   // check if the page has subscribed to 
	   // the custom back button event
	   if (currentpage?.CustomBackButtonAction != null)
	   {
		 // invoke the Custom back button action
		 currentpage?.CustomBackButtonAction.Invoke();
		 // and disable the default back button action
		 return false;
	   }

	   // if its not subscribed then go ahead 
	   // with the default back button action
	   return base.OnOptionsItemSelected(item);
	}
	else
	{
	   // since its not the back button 
	   //click, pass the event to the base
	   return base.OnOptionsItemSelected(item);
	}
}

public override void OnBackPressed()
{
	// this is not necessary, but in Android user 
	// has both Nav bar back button and
	// physical back button its safe 
	// to cover the both events

	// retrieve the current xamarin forms page instance
	var currentpage = (CoolContentPage)
	Xamarin.Forms.Application.
	Current.MainPage.Navigation.
	NavigationStack.LastOrDefault();

	// check if the page has subscribed to 
	// the custom back button event
	if (currentpage?.CustomBackButtonAction != null)
	{
		currentpage?.CustomBackButtonAction.Invoke();
	}
	else
	{
		base.OnBackPressed();
	}
}

 

phewww… that was some long code snippet yeah! fear not child! let me explain…

So as I mentioned before when the user clicks on anything on the default Android navigation bar the above OnOptionsItemSelected() gets fired, where as we will check the clicked item’s id and check for the back button’s default id. Yes the default back button id is the same 16908332 integer in Xamarin Forms – Android applications.

There we will get an instance of the current Xamarin Forms page in the Navigation stack and look if the page has been subscribed to the Custom Back button click event, if so there we will invoke our CustomBackButtonAction, and disable the default click event. If the page hasn’t subscribed to the Action, then we shall pass the click event to the base allowing the default back stack navigation. 🙂 Simple as that! 😀

Now you may see that I have also overridden the OnBackPressed event as well. This is really not necessary if you don’t want to but as a good practice it’s better to override both Nav bar back button and physical back button click events at the same time.

then Xamarin iOS stuff…

Here comes the iOS implementation where we are going to replace the custom Navigation Bar back button and use our own Custom button for the back button as I explained at the beginning. 😀

Now I know when we are to replace the Back button of iOS, we need to replace it with the same similar looking back button, although its custom. This is not really an easy task, because we need to construct the identical back button from the scratch, including the image, fonts and inset values and so on. I have written a complete blog post about this in one of my previous posts. If you want you could refer to it as for the complete explanation here : Creating an identical Custom Navigation Bar Back Button in Xamarin iOS…

But for the sake of this post, I shall post the whole implementation here, but I shall not drill down to detailed explanation. 🙂 You can always prefer to the original post up there.. 😉

Now keep in mind for iOS you need to override the ViewWillAppear() method in your CoolContentPageRenderer class.

So the below code should be placed inside your CoolContentPageRenderer class…

public override void ViewWillAppear(bool animated)
{
     base.ViewWillAppear(animated);
     
     if (((CoolContentPage)Element).EnableBackButtonOverride)
     {
          SetCustomBackButton();
     }
}

private void SetCustomBackButton()
{
     // Load the Back arrow Image
     var backBtnImage = 
     UIImage.FromBundle("iosbackarrow.png");

     backBtnImage = 
     backBtnImage.ImageWithRenderingMode
     (UIImageRenderingMode.AlwaysTemplate);

     // Create our Button and set Edge 
     // Insets for Title and Image
     var backBtn = new UIButton(UIButtonType.Custom)
     {
          HorizontalAlignment =   
          UIControlContentHorizontalAlignment.Left,
          TitleEdgeInsets = 
          new UIEdgeInsets(11.5f, 15f, 10f, 0f),
          ImageEdgeInsets = 
          new UIEdgeInsets(1f, 8f, 0f, 0f)
     };

     // Set the styling for Title
     // You could set any Text as you wish here
     backBtn.SetTitle("Back", UIControlState.Normal);
     // use the white color in ios back button text
     backBtn.SetTitleColor(UIColor.White,
     UIControlState.Normal); 
     backBtn.SetTitleColor(UIColor.LightGray, 
     UIControlState.Highlighted);
     backBtn.Font = UIFont.FromName("HelveticaNeue",
     (nfloat)17);

     // Set the Image to the button
     backBtn.SetImage(backBtnImage, UIControlState.Normal);

     // Allow the button to Size itself
     backBtn.SizeToFit();

     // Add the Custom Click event you would like to 
     // execute upon the Back button click
     backBtn.TouchDown += (sender, e) =>
     {
          // Whatever your custom back button click handling
          if(((CoolContentPage)Element)?.
          CustomBackButtonAction != null)
          {    
            ((CoolContentPage)Element)?.
               CustomBackButtonAction.Invoke();
          }
     };

     //Set the frame of the button
     backBtn.Frame = new CGRect(
          0,
          0,
          UIScreen.MainScreen.Bounds.Width / 4,
          NavigationController.NavigationBar.Frame.Height);

     // Add our button to a container
     var btnContainer = new UIView(
     new CGRect(0, 0, 
     backBtn.Frame.Width, backBtn.Frame.Height));
     btnContainer.AddSubview(backBtn);

     // A dummy button item to push our custom  back button to
     // the edge of screen (sort of a hack)
     var fixedSpace = 
     new UIBarButtonItem(UIBarButtonSystemItem.FixedSpace)
     {
          Width = -16f
     };
     // wrap our custom back button with a UIBarButtonItem
     var backButtonItem = new UIBarButtonItem("",
     UIBarButtonItemStyle.Plain, null)
     {
          CustomView = backBtn
     };

     // Add it to the ViewController
     NavigationController.TopViewController.
     NavigationItem.LeftBarButtonItems 
     = new[] { fixedSpace, backButtonItem };
}

 

Alright there you have it, now keep in mind you need to attach the iosbackarrow.png image to your Xamarin Forms solution’s iOS project’s Resources folder. 😉

As I mentioned above I will not be getting down to the details of the above implementation, but I will explain the nuts and bolts related to this post.

So if you notice above we are creating a custom button and we are subscribing to the TouchDown event of it, which is where we are going to check if the current page has subscribed to the CustomBackButtonAction event or not and proceed with the custom action or default back stack navigation event… 😀

Simple as that! 😉

How to use it, you asked?

Alright let’s consume this beautiful implementation! 😉

So here I’m using our CoolContentPage as a XAML page in my Xamarin Forms solution.

<WhateverYourNamespace:CoolContentPage 
 xmlns="http://xamarin.com/schemas/2014/forms"
 xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
 xmlns:WhateverYourNamespace=
 "clrnamespace:XFNavBarBackBtnClickOverride;
 assembly=XFNavBarBackBtnClickOverride"
 x:Class="XFNavBarBackBtnClickOverride.Page2"             
 Title="Page 3"
 EnableBackButtonOverride="True"
 BackgroundColor="#00bfff">
  <StackLayout
    Spacing="20"
    Padding="20,10,20,10"
    VerticalOptions="Center"
    HorizontalOptions="Center" >

    <Label Text="This is the cool page, 
	which has the Navigation Bar Back button 
	click overriden. How go ahead and click that Back     
        button! ;)"
           FontSize="20"
           HorizontalTextAlignment="Center"
           TextColor="White"/>
    
  </StackLayout>
</WhateverYourNamespace:CoolContentPage>

 

You can notice that I’m setting the EnableBackButtonOverride=”True” property for enabling the overriding of the nav bar custom back button click.

So here’s in the code behind we are subscribing to the CustomBackButtonAction with our Alert dialog asking a verification if the user is sure that they want to go back.

namespace WhateverYourNamespace
{
    public partial class Page2 : CoolContentPage
    {
        public Page2()
        {
            InitializeComponent();
            
            if (EnableBackButtonOverride)
            {
                this.CustomBackButtonAction = async () =>
                {
                    var result = await this.DisplayAlert(null,
                        "Hey wait now! are you sure " +
                        "you want to go back?",
                        "Yes go back", "Nope");

                    if (result)
                    {
                        await Navigation.PopAsync(true);
                    }
                };
            }
        }
    }
}

 

Pay good attention here where if the user confirms they want to go back, then we will manually Pop the page by calling  Navigation.PopAsync() method. If not the back button click event will be ignored thanks to our custom back button click event overriding implementation. 😀

Now keep in mind, subscribing to the Action can be done in many other different ways, code-behind may not be the best practice if you’re heavy MVVM minded, where as may be you could move the custom Action event subscription to the CoolContentPage’s OnAppearing event or base class. All up to your preferences… 😉

Alright, let’s fire it up!

Oh child, just hit that F5! 😉

  

Look at that beauty! 😀 Well the colors and stylings I added myself though.. 😉

So you may grab the code up in my Github: Xamarin-Playground/XFNavBarBackBtnClickOverride

There you go fellas!

Happy coding and share the love! 😀

Udara Alwis out!

FormsAppCompatActivity is not calling OnOptionsItemSelected Xamarin Android…

So have you Sub-classed your MainActivity from FormsAppCompatActivity which is also the default Parent Class for MainActivity in Xamarin Forms Android project? but you can’t get a hit on the OnOptionsItemSelected override?

Welcome to another flash post!

Recently I tried..

So recently I tried to override the navigation bar Back button click on Android in one of my Xamarin Forms applications.

but Unfortunately…

So one way to handle this is by overriding the OnOptionsItemSelected method in MainActivity, which is the Single Activity that all our Xamarin Forms Views get’s laid upon. But unfortunately I wasn’t able to get a hit on the above override method.

then I noticed…

So this project solution was created on Visual Studio with Xamarin version 4.2.2.11, where as I noticed that the MainActivity was sub-classing from the FormsAppCompactActivity instead of good old FormsApplicationActivity which was the previous parent class for MainActivity.

No sense…

Since it did not make sense I turned to the Xamarin Forums, and lucky enough I found this thread, where few others were also experiencing the same issue.

https://forums.xamarin.com/discussion/comment/218663#Comment_218663

Reason? Probably…

So according to the forums, it appears to be some missing bug in Xamarin Android version, where as the Android Toolbar doesn’t get referenced to the Activity. Where as since we are using FormsAppCompactActivity as the base, the Toolbar in action is the Android.Support.V7.Widget.Toolbar, not the good old Android.Widget.Toolbar, which for some reason doesn’t get attached to the Activity.

Solution…

Well if you had gone through the above forum you may have found the solution already… Basically we just need to set the Action Bar reference in the Activity in your OnCreate() method.. 😉

Android.Support.V7.Widget.Toolbar toolbar 
	= this.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
SetSupportActionBar(toolbar);

 

or if I’m to share my MainActivity…

public class MainActivity : FormsAppCompatActivity
{
	protected override void OnCreate(Bundle bundle)
	{
		TabLayoutResource = Resource.Layout.Tabbar;
		ToolbarResource = Resource.Layout.Toolbar;

		base.OnCreate(bundle);

		global::Xamarin.Forms.Forms.Init(this, bundle);
		LoadApplication(new App());
		
		Android.Support.V7.Widget.Toolbar toolbar 
			= this.FindViewById<Android.Support.V7.Widget.Toolbar>(Resource.Id.toolbar);
		SetSupportActionBar(toolbar);
	}
}

 

Well there you have it! Solved! 😀

Cheers!

“UnpackLibraryResources” or “MTouch” task failed, during compile?

Now this is regarding the mysterious build error, “UnpackLibraryResources” task failed and the “MTouch” task failed, which unfortunately occurs out of nowhere in Xamarin Forms projects…

It all started…

So sometimes when I try to build and run my perfect Xamarin Forms project in Visual Studio, by the way which has no compilation issues, suddenly breaks down with a compilation error saying “UnpackLibraryResources” task failed and the “MTouch” task failed…
This was a complete puzzle to me, since there were no errors in the code, and this never occurred with any small scale project solutions, only with those massive enterprise scale projects at work.

I tried to look for a solution…

So I tried clean and rebuild, reopen Visual Studio, and blah blah many things.

Weirdly enough…

So one last destination I tried was restarting Windows and re-opening Visual Studio, which actually worked!
It got me thinking, may be this has to do something with the resource usage of the PC, may be the build process is getting disturbed by some system activity in the background.

then I found this…

So I opened up Task Manager, and kept an eye on it, while running the compile and rebuild of my project.

BOOM! 😮

I stumbled upon a crazy observation, whereas every time the above error occurs and the build fails, the Disk usage was showing up as below in the Task Manager.

unpacklibraryresources-compilation-error

And then time during the following error I noticed the same Disk usage as well.

mtouch-task-failed-compilation-error

Its very rare that VS could cause such a massive disk usage during build and run, and even if it did, why would the build process fail in such manner?

Reason behind this…

So I took a look at the Processes tab in the Task Manager and noticed that “Microsoft Compatibility Telemetry” process was hogging up the Disk usage, which is apparently the process that comes built into Windows 10 to collect and send our Usage Data to Microsoft.

And believe me this process was dominating the whole Read and Write usage of the Disk, that it was spiked up to over 90% disk usage only for this process. 😮

Now I don’t have any problem with Microsoft collecting my personal usage data for the reason of “improving their product” (which is what they say at least), but if it’s disturbing my day to day work, then you’re crossing a line! lol

So I killed the above process and re-ran my build,

BOOM! IT WORKED! 😀

And then another time the same issue occurred, I took a look at the Task Manager and noticed that my Anti-Virus which is “Kaspersky was running a scheduled Rootkit Scan” and it was hogging up the Disk usage over 90%!

So I cancelled the scan process and re-ran my build,

BOOM! IT WORKED! 😀

So now you know….

So as of my above experience you can clearly see that those build errors occur due to

excessive usage of Disk’s Read and Write by other Processes…

and it’s somehow disturbing the Build process for obvious reasons.

Now I’m not saying the above errors occur only for this specific reason, but in case if you couldn’t find a reason, then you may have to look into this aspect as I did! 😉

There you have it, I just shared my experience with yol, hope it may help someone!

Cheers! Stay awesome Devs!

😀

Udara Alwis OUT!

Wait… How could I handle Click event of a Custom Renderer Button in Xamarin Forms ? :|

Now we all know how Xamarin allows your to override the renderering process of any given UI control from native level and do any sort of modifications through Custom Renderers.

Completely overriding Xamarin Forms Control in Custom Renderer?

It even allows you to completely override the whole Control that’s associated with Xamarin Forms type Control and replace it with a completely native type Control. Specifically in cases like where you override the Control property with SetNativeControl() method in your Custom Renderer.

But when you do that…

But what happens when you complete replace and override the associated default control for your renderer is that, you will lose the access to Events of that particular control.

To be specific…

Let’s take a look at the following Custom Renderer…

[assembly: ExportRenderer(typeof(CustomButton), typeof(CustomButtonRenderer))]
namespace WhateverYourNamespace.Droid
{
    public class CustomButtonRenderer : ButtonRenderer
    {
        protected override async void OnElementChanged(ElementChangedEventArgs<CustomButton> e)
        {
            base.OnElementChanged(e);
            
            if (e.NewElement != null)
            {
		Android.Widget.Button nativeButton = new Android.Widget.Button();
			
                SetNativeControl(nativeButton);
            }
        }
     }
}

 

There you can see we are completely replacing the default Button Control associated with the Renderer with our own native Button control.

When you do that, since you’re completely replacing everything, you will lose access to all the events and properties associated with the default control. Such as Button Click, Touch Events and so on.

As in try to subscribe to your CustomButton’s default Clicked event, it won’t fire up during run time, since it been overridden by the native button control.

So how to handle events?

Yep in that case, we need to handle those events manually and map those necessary events from our Native button control to Xamarin Forms level properties and events.

Custom Events…

Yep this is how you manually create an Event for your Custom Button.

public class CustomButton : Button
{
	public event EventHandler ClickedCustom;
	
	public void SendCustomClicked()
	{
		EventHandler eventHandler = this.ClickedCustom;
		eventHandler?.Invoke((object)this, EventArgs.Empty);
	}
}

 

And then upon the Native Button’s Click event we invoke this event from the Custom Renderer level. 🙂

nativeButton.ClickEvent += (sender, args) =>{
	view.SendCustomClicked();
}

 

And then at the run time it will fire up the ClickedCustom event for your Custom Button in response of the native button’s click.

So now you can subscribe to ClickedCustom event instead of default Clicked event in your Xamarin Forms code and get the response upon the custom button click.

Any other type of events and properties…

You could follow the same pattern for any other type of event you wish to handle, and even properties such as Text, Color and blah blah… 😉

TADAAA! 😀

Enjoy!

Is it possible to add a Text Shadow in Button with Xamarin Forms ? ;)

Let’s face it, sometimes your UX Lead comes up with crazy screen designs, and its us developers who has to go through the pain of delivering the design implementation accordingly. Yeah one of those moments I went through was when I had given a task to implement a Button Control with Text Shadow effect in Xamarin Forms

More descriptively, create a button which has a shadow effect underneath its internal Text?

Yeah some of your wonder why would someone even pay attention to such tiny details, yeah well you know UX fellows. 😉 lol

1

Well anyways you can’t really deny the text shadow does add some beauty to the button as you can see from above! 😉

Is this possible?

Anyhow, this is not possible in Xamarin Forms default Button, oh well you can’t even set an Image for the button’s background in Xamarin Forms unfortunately.

So the solution?

Well as usual we shall be praising Custom Renderers for our rescue. 😀 Hence such effects are available by default in Android and iOS Button controls.

So for you Github-errrs you may grab my code up in here: Xamarin-Playground/XFTextShadowButtonControl

First subclass our Custom Button…

Let’s create our TextShadowButton control by subclassing the Xamarin Forms Button control. Also you need to add a property to set the Shadow Color in this awesome button control. 😀

namespace WhateverYourNamespace
{
    public class TextShadowButton : Button
    {
		public static readonly BindableProperty TextShadowColorProperty =
        BindableProperty.Create(
        nameof(TextShadowColor),
        typeof(Color),
        typeof(TextShadowButton),
        Color.Gray);

        /// <summary>
        /// Gets or Sets TextShadowColor property
        /// </summary>
        public Color TextShadowColor
        {
	        get
	        {
		        return (Color)GetValue(TextShadowColorProperty);
	        }
	        set
	        {
		        SetValue(TextShadowColorProperty, value);
	        }
        }
    }
}

 

There you go, and let’s set the default Shadow color as Gray. 😉

So iOS stuff?

Next time for the Custom Renderer for this control in iOS..

[assembly: ExportRenderer(typeof(TextShadowButton), typeof(TextShadowButtonRenderer))]
namespace WhateverYourNamespace.iOS
{
    public class TextShadowButtonRenderer : ButtonRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Button> e)
        {
            base.OnElementChanged(e);

            var view = (TextShadowButton) Element;
            if (view == null) return;
            
            // Adding the Button text shadow effect
            Control.TitleLabel.ShadowOffset = new CGSize(0, 0.25);
            Control.SetTitleShadowColor(((TextShadowButton)Element).TextShadowColor.ToUIColor(), UIControlState.Normal);
        }
    }
}

 

The native iOS Control that associates with Xamarin Forms Button is UIButton, which has the properties called, TitleLabel.ShadowOffset and TitleShadowColor that you could use to add the Shadow effect to our Button Text 😉

then Android stuff?

Next is the Android Renderer for our TextShadowButton

[assembly: ExportRenderer(typeof(TextShadowButton), typeof(TextShadowButtonRenderer))]
namespace WhateverYourNamespace.Droid
{
    public class TextShadowButtonRenderer : ButtonRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Button> e)
        {
            base.OnElementChanged(e);

            var view = (TextShadowButton)Element;
            if (view == null) return;

            // Adding the Button text shadow effect
            Control.SetShadowLayer(4, 0, 2, ((TextShadowButton)Element).TextShadowColor.ToAndroid());
        }
    }
}

 

So in native Android Button, we have the ShadowLayer property which we could use to simulate a shadow effect on the Button Text. There we have set the shadow radius and pointed the shadow view lower than the text view by setting the Y axis to value 2.

time for Consumption of this sweetness! 😉

Alright, add this sweetness into your page and take a look…

<StackLayout>
	<Button Text="This is normal Button" BackgroundColor="#f8c220" TextColor="White"/>
	<local:TextShadowButton Text="Awesome Button with Shadow" BackgroundColor="#f8c220" HeightRequest="37" TextColor="White"/>
</StackLayout>

 

So what are you waiting for? Hit F5 and Run! 😀

2

screen-shot-2017-02-06-at-8-59-25-pm  nexus-5-lollipop-screenshot-2

WOOT! WOOT! 😀

Share the beauty! 😉 Cheers!

Awesome Xamarin Forms Label with HTML Text Formatting…

Why would you wanna use a WebView when you could use your Label to display HTML mark up text in your Xamarin Forms app? 😉

How it all started?

Well some times back I had to implement a Xamarin Forms Label which can display HTML formatted text…

The problem with Xamarin Forms Label?

Well of course you would tell me to use the FormattedText property built into Xamarin Forms Label. But before you say that do you even know how limited that property is? and you have to break up your string in to pieces and rebuild it with Span blocks, and also there’s only a few text formatting options available. Usually HTML has a ton of text formatting options, which you can even get close to with the default Xamarin Forms Span block customization.

So the default Xamarin Forms Label can not do any help at this case.

Solution?

Well we all know it’s super easy to parse HTML text to be rendererd in a Label with Android and iOS native implementation. That’s why I had to drill down to native level and come up with a Custom Label that could display HTML markup text. 😀

Without further due, let’s jump into it! 😉

Create the Custom Control…

So as usual let’s create our Custom Label by subclassing Xamarin Forms Label control.

namespace WhateverYourNamespace
{
    public class HtmlFormattedLabel : Label
    {

    }
}

 

Nothing fancy there… Next are the big stuff!

Xamarin Android implementation…

So here’s the renderer for our HtmlFormattedLabel

[assembly:ExportRenderer(typeof(HtmlFormattedLabel), typeof(HtmlFormattedLabelRenderer))]
namespace WhateverYourNamespace.Droid
{
    public class HtmlFormattedLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);

            var view = (HtmlFormattedLabel)Element;
            if (view == null) return;
            
            Control.SetText(Html.FromHtml(view.Text.ToString()),TextView.BufferType.Spannable);
        }
    }
}

 

So what we basically do here is native Android TextView through the Control property of our renderer and access the SetText() method, and  directly use the Android HTML parser to set your HTML Text.

Xamarin iOS implementation…

Next is our iOS renderer for the custom control.

[assembly:ExportRenderer(typeof(HtmlFormattedLabel), typeof(HtmlFormattedLabelRenderer))]
namespace WhateverYourNamespace.iOS
{
    public class HtmlFormattedLabelRenderer : LabelRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Label> e)
        {
            base.OnElementChanged(e);
            
            var view = (HtmlFormattedLabel)Element;
            if (view == null) return;

            var attr = new NSAttributedStringDocumentAttributes();
            var nsError = new NSError();
            attr.DocumentType = NSDocumentType.HTML;
            
            Control.AttributedText = new NSAttributedString(view.Text, attr, ref nsError);
        }
    }
}

 

So here what we do is, we access the native iOS UILabel through the Control property and directly set the AttributedText property with our natively parsed HTML string. 😉

Now unlike Android, I wasn’t much familiar with iOS implementation of HTML text parsing, therefore I took some help from this thread for the above implementation How to display html formatted text in a UILabel ?.

KABOOM! EASY!

Let’s consume this Awesome Label! 😉

Alright time to use the Awesome Label we just created in Xamarin Forms!

Content = new StackLayout
{
	VerticalOptions = LayoutOptions.Center,
	Padding = new Thickness(20,0,20,0),
	Spacing = 30,
	Children = {
		new Label {
			HorizontalTextAlignment = TextAlignment.Center,
			TextColor = Color.Black,
			Text = "Welcome to the awesome HTML Formatter Label" +
			"Control by ÇøŋfuzëÐ SøurcëÇødë!"
		},
		new HtmlFormattedLabel()
		{
			FontSize = 14,
			TextColor = Color.Black,
			Text = 
			   "<html><body><Center>" +
			   "<font size='6'>" +
			   "This is a html formatted text," +
			   "so this is <b>bold text</b>... " +
			   "and this is <u>underline text</u>... " +
			   "and this is <strike>strike through text</strike>... " +
			   "and finally this is <i>italic text</i>... " +
			   "<br />" +
			   "Ops this is html line break..." +
			   "<br />" +
			   "And this is <sup>superscripted</sup> html text."+
			   "</font>" +
			   "<Center></body></html>",
		}
	}
}

 

So here I’m using our HtmlFormattedLabel control and directly setting a HTML formatted text to its Text property. 😀

Now hit F5 and Run that beautiful code! 😉

screen-shot-2017-02-05-at-4-08-31-pmnexus-5-lollipop-screenshot-3

There you have it fellas! 😀

Now you may grab this code from my github: Xamarin-Playground/XFHtmlFormattedLabelControl

Enjoy!

And pass on to another Developer by sharing it! 😉

So I played around with Xamarin Forms Control Templates!

Yes I did and I came up with something pretty cool. Do you want to change your app’s theme on demand at run time? or load a different template for your pages at run time? or even simply change the app’s colors on demand?

Oh yeah Xamarin Forms Control Template gives the answer to all of that! 😉 Here what I built with it! 😀

xf-control-templates-ios xf-control-templates-android

Pretty cool eh! 😀

So basically what I built was a simple app where you could dynamically change the App background  color theme and change the change the App theme style on demand.

As you can see you can change the color theme of the app by clicking on the color buttons and change the theme style by clicking on the theme change button, which loads a different theme for the App if you closely notice.

The honest inspiration for this is that I remember back in the days when I was installing Windows 8 in my laptop, at the first time boot up, they ask you to choose the color theme you would like to use.

installation-7

Where it presents you with a beautiful color pallet and when you click on any of those colors the whole page changes the color accordingly, so I wanted to build something like that for the fun someday. 😉

So here we go… 😀

What are Xamarin Forms Control Templates?

Xamarin.Forms control templates provide the ability to easily theme and re-theme application pages at runtime. – Xamarin Docs 

Nuff said, if you want to learn more about it, read the documents. Here I’m going to explain how you could achieve the above cool stuff using Control Templates for Xamarin Forms.

Xamarin Forms Control Templates Binding?

I have used the Binding in order to change the template color at runtime. 🙂 If you’re not familiar with this concept, you may read up here: Xamarin Docs

We are keeping a public Property for the Theme color in our ContentPage, and binding our Control Template’s color values to that property. So at the run time whenever we change the Color property, it will get reflected to whatever the Template and the background color will change accordingly. 😉

Otherwise we would have to create different Control Templates for every single color, which will be very heavy and long code, but thanks to Binding we could do it with ease as described above.

Let me walk you through…

1. Creating templates…

First of all let’s create our templates, we are going to create two templates with different styles, as show in the below screenshots of the finished implementation.

simulator-screen-shot-1-jan-2017-2-53-32-pm  simulator-screen-shot-1-jan-2017-2-53-45-pm

  1. Template Header and footer will have a background and simple Label for both header and footer.
  2. Template Header will have one label with with a white background color, and footer will have two labels with white background color.

For now just forget about the color and we will focus on the initial Template Design.

Alright now let’s get to work.

Let’s begin by creating the project, and make sure to create XAML based Xamarin Forms project. Then let’s create our Control Templates in the App.xaml file, within the Application.Resources tag by adding them to the global ResourceDictionary, so that they could be accessed in anywhere of the app at runtime.

You can create any number of templates as you wish and name them in anyways you prefer. 😉 More themes the merrier…

<Application.Resources>
<ResourceDictionary>

  <!--template theme 1-->
  <ControlTemplate x:Key="MyTemplate1">
    ...
  </ControlTemplate>

  <!--template theme 2-->
  <ControlTemplate x:Key="MyTemplate2">
    ...
  </ControlTemplate>

</ResourceDictionary>
</Application.Resources>

 

le template 1…

Alright let’s create our first Control Template.

<!--template theme 1-->
<ControlTemplate x:Key="MyTemplate1">
<Grid>
  <Grid.RowDefinitions>
    <RowDefinition Height="0.1*" />
    <RowDefinition Height="0.8*" />
    <RowDefinition Height="0.1*" />
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
    <ColumnDefinition Width="0.05*" />
    <ColumnDefinition Width="0.95*" />
  </Grid.ColumnDefinitions>

  <!--template header-->
  <!--use of template binding for color-->
  <BoxView Grid.ColumnSpan="2" Color="{TemplateBinding Parent.ThemeColor}" />
  <Label Grid.Row="0" Grid.Column="1"
         Text="this is my theme style 1"
         TextColor="White"
         VerticalOptions="Center" />
  <!--template header-->

  <!--your page content goes in here-->
  <ContentPresenter Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" />

  <!--template footer-->
  <!--use of template binding for color-->
  <BoxView Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" Color="{TemplateBinding Parent.ThemeColor}" />
  <Label Grid.Row="2" Grid.Column="1"
         Text="template 1 (c) Udara Alwis 2016"
         TextColor="White"
         VerticalOptions="Center" />
  <!--template footer-->
</Grid>
</ControlTemplate>

 

There you have it, as you can see we have created a template with a Grid where we are aligning the page content in the middle  as the ContentPrensenter and the Header and Footer accordingly at top and bottom. We have added simple Labels to each Header and Footer with some text in it.

You can also notice that we are using Template property Binding to set the Background color of our Template. Color=”{TemplateBinding Parent.ThemeColor}”

So at the run time the Color will change according to the “ThemeColor” property which we will be implementing in the ContentPage.

You can use Binding to Change any property in your Control Templates thanks to awesomeness of Xamarin Forms! 😀

le template 2…

Now here’s our second Control Template.

<!--template theme 2-->
<ControlTemplate x:Key="MyTemplate2">
<Grid>
  <Grid.RowDefinitions>
	<RowDefinition Height="0.1*" />
	<RowDefinition Height="0.8*" />
	<RowDefinition Height="0.1*" />
  </Grid.RowDefinitions>
  <Grid.ColumnDefinitions>
	<ColumnDefinition Width="0.05*" />
	<ColumnDefinition Width="0.35*" />
	<ColumnDefinition Width="0.55*" />
	<ColumnDefinition Width="0.05*" />
  </Grid.ColumnDefinitions>

  <!--template header-->
  <!--use of template binding for color-->
  <BoxView Grid.ColumnSpan="4" Color="{TemplateBinding Parent.ThemeColor}" />
  <Label Grid.Row="0" Grid.Column="1"  Grid.ColumnSpan="2"
		 Text="this is my theme style 2"
		 TextColor="Black"
		 BackgroundColor="White"
		 VerticalOptions="Center" />
  <!--template header-->

  <!--your page content goes in here-->
  <ContentPresenter Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="4" />

  <!--template footer-->
  <!--use of template binding for color-->
  <BoxView Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="4" Color="{TemplateBinding Parent.ThemeColor}" />
  <Label Grid.Row="2" Grid.Column="1"
		 Text="template 2"
		 TextColor="Black"
		 BackgroundColor="White"
		 VerticalOptions="Center" />
  <Label Grid.Row="2" Grid.Column="2"
		 Text="(c) Udara Alwis 2016"
		 TextColor="Black"
		 BackgroundColor="White"
		 VerticalOptions="Center"/>
  <!--template footer-->
</Grid>
</ControlTemplate>

 

As you can see the difference of this Template is that we have added extra columns to the Grid container and added extra labels to fill in. Also you may have noticed that we are setting the Label background to White color in this template.

Alright there goes our two templates in this example. Next let’s implement the design for our ContentPage.

2. ContentPage design stuff…

So those two Template themes are now ready to be applied for any ContentPage in our App.

Next let’s lay down the design for our content page. Remember hence we are using Control Templates, we need to implement our UI in a way our page could use those templates, which is by,

having a ContentView which will position itself in the ContentPresenter in the Templates once we bind to them.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:XFControlTemplateThemes"
             x:Class="WhateverYourNamespace.MainPage">

  <ContentView x:Name="contentView"
               ControlTemplate="{StaticResource MyTemplate1}">
    <ContentView.Padding>
      <OnPlatform x:TypeArguments="Thickness" iOS="0,20,0,0" />
    </ContentView.Padding>

   <!-- Your Page Content-->

  </ContentView>
</ContentPage>

 

You may have noticed that I have bound our ContentView ControlTemplate  property to one of the Templates we created in the App.xaml yeah? Yep exactly that’s because since we placed those templates in the App’s global level, we can directly access those properties from anywhere in our app. So as of the defualt ControlTemplate I have set it to the “MyTemplate1” template we created. So when the page loads it will be decorated with that. 😉

Now let’s take a look at the Page content design which will be placed inside the ContentView above. 🙂

Now keep in mind you can implement whatever the design you want to your Page body, but for this example basically we need to have a button to switch in between the two themes we created above and another bunch of buttons to change the color of those themes (something like a color pallet). So here we go…

<StackLayout VerticalOptions="CenterAndExpand" Padding="10,0,10,0">

  <Label Text="Welcome to the Dynamic Theme Changer app!"
		 HorizontalTextAlignment="Center"
		 FontSize="20"
		 VerticalOptions="Start"
		 HorizontalOptions="Center" />

  <Grid Padding="0,20,0,20">
	<Label Text="click below to change the theme on the go"
		   HorizontalTextAlignment="Center"
		   HorizontalOptions="Center" />
	<Button Text="change current theme template" Grid.Row="1"
				Clicked="OnButtonClicked" />

	<Grid.RowDefinitions>
	  <RowDefinition Height="*" ></RowDefinition>
	  <RowDefinition Height="40" ></RowDefinition>
	</Grid.RowDefinitions>
  </Grid>

  <Grid Padding="0,20,0,20">

	<Label Text="click below to change the theme color on the go"
		   HorizontalTextAlignment="Center"
		   HorizontalOptions="Center"
		   Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="10"/>

	<Button BackgroundColor="#ff0000" Grid.Row="1" Grid.Column="0" Clicked="OnColorChangeButtonClicked" />
	<Button BackgroundColor="#ff8000" Grid.Row="1" Grid.Column="1" Clicked="OnColorChangeButtonClicked" />
	<Button BackgroundColor="#ffff00" Grid.Row="1" Grid.Column="2" Clicked="OnColorChangeButtonClicked" />
	<Button BackgroundColor="#00ff40" Grid.Row="1" Grid.Column="3" Clicked="OnColorChangeButtonClicked" />
	<Button BackgroundColor="#00ffff" Grid.Row="1" Grid.Column="4" Clicked="OnColorChangeButtonClicked" />
	<Button BackgroundColor="#0080ff" Grid.Row="1" Grid.Column="5" Clicked="OnColorChangeButtonClicked" />
	<Button BackgroundColor="#4000ff" Grid.Row="1" Grid.Column="6" Clicked="OnColorChangeButtonClicked" />
	<Button BackgroundColor="#bf00ff" Grid.Row="1" Grid.Column="7" Clicked="OnColorChangeButtonClicked" />
	<Button BackgroundColor="#ff0080" Grid.Row="1" Grid.Column="8" Clicked="OnColorChangeButtonClicked" />
	<Button BackgroundColor="#ff0040" Grid.Row="1" Grid.Column="9" Clicked="OnColorChangeButtonClicked" />

	<Grid.RowDefinitions>
	  <RowDefinition Height="*" />
	  <RowDefinition Height="40" />
	</Grid.RowDefinitions>
	<Grid.ColumnDefinitions>
	  <ColumnDefinition Width="0.1*" />
	  <ColumnDefinition Width="0.1*" />
	  <ColumnDefinition Width="0.1*" />
	  <ColumnDefinition Width="0.1*" />
	  <ColumnDefinition Width="0.1*" />
	  <ColumnDefinition Width="0.1*" />
	  <ColumnDefinition Width="0.1*" />
	  <ColumnDefinition Width="0.1*" />
	  <ColumnDefinition Width="0.1*" />
	  <ColumnDefinition Width="0.1*" />
	</Grid.ColumnDefinitions>
  </Grid>

</StackLayout>

 

Behold my beautiful UI. 😉 As you can see the first button will be switching in between the themes we created before, and them there’s a whole another set of buttons (color pallet buttons) with different background colors, which points to the same click event. Those buttons will be changing the template color by changing the ThemeColor property I mentioned earlier, which we are going to implement next. 🙂

3. ContentPage code-behind…

Now this is where we put things together, in your MainPage.cs code behind. Which we are handling all the theme changes and color changes on the go. 😉

So here are what we are going to implement here…

  1. ThemeColor public property to be used by the Templates for Color changing feature
  2. Load the control templates to be used in this page for run time theme changing
  3. Handle the run time theme switching functionality (switch the themes in between the templates we created before)
  4. Handle the tun time them color switching functionality (switch the themes between different color as show in those color buttons)
public partial class MainPage : ContentPage
{
	public static readonly BindableProperty ThemeColorProperty =
		BindableProperty.Create("ThemeColor", typeof(Color), typeof(MainPage), Color.Red);
	/// <summary>
	/// Gets or Sets the theme color for the template
	/// </summary>
	public Color ThemeColor
	{
		set { SetValue(ThemeColorProperty, value); }
		get { return (Color)GetValue(ThemeColorProperty); }
	}

	private bool _originalTemplate = true;
	private ControlTemplate _myTemplate1;
	private ControlTemplate _myTemplate2;

	public MainPage()
	{
		InitializeComponent();

		_myTemplate1 = (ControlTemplate)Application.Current.Resources["MyTemplate1"];
		_myTemplate2 = (ControlTemplate)Application.Current.Resources["MyTemplate2"];
	}

	void OnButtonClicked(object sender, EventArgs e)
	{
		// switching to the next theme
		_originalTemplate = !_originalTemplate;
		contentView.ControlTemplate = (_originalTemplate) ? _myTemplate1 : _myTemplate2;
	}

	private void OnColorChangeButtonClicked(object sender, EventArgs e)
	{
		if (((Button)sender) != null)
		{
			var sender1 = ((Button)sender);

			// Change the theme color according 
			// to the selected button color
			ThemeColor = sender1.BackgroundColor;

			// this will update the ThemeColor property
			// and reflect to the Control template
		}
	}
}

 

You can see I have implemented the ThemeColor property where our Templates will be binding their Color properties to. Then take a look at the event OnColorChangeButtonClicked which is the event that is fired by the set of buttons with different colors as we implemented in the UI. So inside this event we are retrieving the button’s background color and setting that value to our ThemeColor property, which will in return reflect to the Template that has been loaded to the page at that moment.

And then in the Constructor we are loading the two templates we created before into our page by accessing the Application Resources dictionary so we can use those instances to change the them on the go.

Inside the OnButtonClicked event we are switching between the two template themes we have loaded above.

Finally hit F5!

Alright that’s it for the coding. Now save it and hit F5 to see the magical beauty of Xamarin Forms! 😉

xf-control-templates-ios  xf-control-templates-android

So you can see clearly that when you click on the “change current theme template” button, the theme immediately changes to the next template.

And then you click on any of the color pallet buttons you can see the theme background color changes accordingly. Beautiful isn’t it? 😉

There you have it fellas!

Now as for them lazy people, you could straight away grab the code up in my github: Xamarin-Playground/XFControlTemplateThemes

Enjoy and share! 😀

– Udara Alwis

So I created a Popup with Transparent background in Xamarin Forms… ;)

Alright so I was supposed to post this few months back, before I got stuck with my day job which led to temporary put my blog on hold. Either way, recently I managed to find some free time off from work, so I would go ahead and post this with some necessary updates! 🙂

So a while back I was asked to create a Transparent popup control in Xamarin Forms, as ordered by my boss (a very cool guy) to be used for instances such as Loading Spinner screens, and Popup Dialog boxes.

Xamarin Forms ContentPage ? Transparency ?

So I tried to derive my custom control from the default ContentPage control of Xamarin Forms, by setting the Background color of the page to Transparent.

Although I’ve failed by pushing the Page to NavigationStack, I managed to get it working as a Modal page by pushing it to the ModalStack but only on Android platform.

Let’s get into coding…

Alright let’s get into some coding, first create the Custom Control by deriving from ContentPage.

    public class TransparentPopup : ContentPage
    {
        public TransparentPopup()
        {
            // set the background to transparent color 
            // (actually darkened-transparency: notice the alpha value at the end)
            this.BackgroundColor = new Color(0,0,0, 0.4);
        }
    }

 

Although this implementation worked out of the box on Android, it didn’t work as expected on iOS, probably due to the differences the page drawing process of Android and iOS, specially as a popup View.

So I played around with iOS and managed to get it working. So let’s create a custom renderer for iOS.

The deal here is to prepare the Popup to draw over the Parent View Controller which is the previous page. So that we could see through the Popup to see the page underneath which is the parent view. Becase in iOS when a new View Controller is introduced the previous View Controller’s View gets removed from the Window.

[assembly: ExportRenderer(typeof(TransparentPopup), typeof(TransparentPopupRenderer))]
namespace WhateverYourNamespace.iOS
{
    public class TransparentPopupRenderer : PageRenderer
    {
        protected override void OnElementChanged(VisualElementChangedEventArgs e)
        {
            base.OnElementChanged(e);
        }

        public override void DidMoveToParentViewController(UIViewController parent)
        {
            base.DidMoveToParentViewController(parent);

            if (ParentViewController != null)
            {
                // Preparing the view to get the presentation of the parent view for the background
                ParentViewController.ModalPresentationStyle = UIModalPresentationStyle.OverCurrentContext;
            }
        }

        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Setting the background color to transparent when the view is appearing
            View.BackgroundColor = UIColor.Clear;
        }
    }
}

 

DidMoveToParentViewController called when the current view gets added to the parent ViewController, so at that point we will set the ModalPresentationStyle of the parent controller, to OverCurrentContext property which will draw our popup view over the previous view.

Well that’s the iOS Custom Renderer, and like I mentioned before we are not going to be needing a Custom Rendering for Android, hence the Modal Page get’s drawn directly above the previous page view.

So let’s put it to use eh! 😉

 Navigation.PushModalAsync(new TransparentPopup());

 

Yep! that’s pretty much it. 🙂

Thou shalt grab em code up on my github: XFTransparentPopup

Cheers!

Wait for it……..

A journey through time…

*fast forwards time…*

*forwarding through time 4-6 months…*

*passing through them late night work hours at office…*

*days of procrastinating and laziness…*

*till this date (November, 2016)*

So after time travelling to this date I updated my local Xamarin installation and this project solution’s Xamarin references, hoping to refresh everything an finally finish off this article.

BOOM! EVERYTHING BROKEN!

Yep since the upgrade to the latest Xamarin references the above implementation has broken and transparency is working no more for the Modal Pages.

Hence it appears to be a change in the Xamarin Core implementation for ContentPage and the rendering process of Modal Pages with the latest update, there had been some other complaints in the Xamarin Forums regarding this. Although whatever the changes Xamarin Forms team has done, I’m sure they had their reasons. This seems to be occurring from all the new Xamarin versions, since I’ve been trying out few fresh Project solutions as well

Looks like I need to find an alternative (until I find a workaround)….

Alternative?

Very well… lucky enough I stumbled upon this awesome library called, Rg.Plugins.Popup! Which literally saved me tons of time. This is a Xamarin Forms library that allows you to create Transparent Popup pages, allowing you to open any ContentPage control as a popup page with full transparency background.

And this library solves a massive problem xamarin developers have been facing, which is the Transition animation control between pages, where as in default Xamarin Forms navigation stack, we can not modify the Transition animations between pages, but with this library, it’s all possible and we could add our own custom animations for page transitions.

capture

Go ahead visit their Github page for description: https://github.com/rotorgames/Rg.Plugins.Popup

Looks very promising indeed. Alright let’s try it out!

Praising le third party library…

Alright just for basics add the Rg.Plugins.Popup library to your Xamarin Forms project from Nuget.

This library provides us a base control that is called PopupPage, which gives you full Transparency background properties, therefore instead of deriving from ContentPage, now we are going to derive from PopupPage to our Transparent Page.

namespace WhateverYourNamespace
{
    public class TransparentPopup : PopupPage
    {
        public TransparentPopup()
        {
            // set the background to transparent color 
            // (actually darkened-transparency: notice the alpha value at the end)
            this.BackgroundColor = new Color(0, 0, 0, 0.4);
        }
    }
}

 

There you go, now let’s add some decorations to our Transparent Popup Page. 😉

public TransparentPopup()
{
	Button btnClose = new Button() { Text = "Close this" };
	btnClose.Clicked += BtnCloseOnClicked;

	Content = new StackLayout()
	{
		BackgroundColor = Color.Transparent,
		Children =
		{
			new Label()
			{
				Text = "Hello from Transparent Modal Page",
				FontSize = 18,
				TextColor = Color.White,
				HorizontalTextAlignment = TextAlignment.Center
			},
			new ActivityIndicator()
			{
				IsRunning = true
			},
			btnClose,
		},
		VerticalOptions = LayoutOptions.Center,
		Padding = new Thickness(10,0,10,0),
	};

	// set the background to transparent color 
	// (actually darkened-transparency: notice the alpha value at the end)
	this.BackgroundColor = new Color(0, 0, 0, 0.4);
}

private void BtnCloseOnClicked(object sender, EventArgs eventArgs)
{
	// Close the modal page
	PopupNavigation.PopAsync();
}

 

Alright, shotgun! There we have added a welcome Label, Activity indicator and a Button to close the popup.

Something important!

And as you can see on the BtnCloseOnClicked event, we are accessing a property called PopupNavigation, instead of default Xamarin Forms Navigation property, to remove the page from Stack.

Well its because Rg.Plugins.Popup maintains its own Popup-Navigation Stack which keeps references to the Popups of it’s own kind, which derives from the PopupPage. So we need to access that property to remove the page from our Navigation stack.

It also provides a Page background click behavior, which is if the user clicks on the background of the page, we could trigger an event to exit the page. Well in my case I didn’t want that to happen so let’s disable it. 😀

protected override bool OnBackgroundClicked()
{
	return false;
}

 

Alright, let’s consume this fella right now as below,

Navigation.PushPopupAsync(new TransparentPopup());

 

Now you must have expected to use the ordinary Navigation.PushModalAsync() as what we normally do in Xamarin Forms, yes of course you could do the same to open this Transparent Popup page, but you may loose the Transparency and ability to override the Navigation Transition animations.

Therefore we are using the PushPopupAsync() extension method that’s provided by this library, which is pretty cool. Now the reason for this I shall explain later in this post.

Alright! Let’s run this fella and see for ourselves! 🙂

nexus-5-lollipop-screenshot-1  simulator-screen-shot-6-dec-2016-10-46-02-am

WOOT! WOOT!

there you go! 😀

For You lazy people may fetch my code up on my githubXFTransparentPopupUpdate

Enjoy!

Important after-notes to share…

1. Page Transition Animations

In default Xamarin Forms Navigation we do not have the access to Page Transition Animations, hence we have to suck it up with the default boring Transition animations of Xamarin Forms.

But thanks to this library, Rg.Plugins.Popup maintains its own Popup-Navigation Stack which to allow us to control the Page Navigation Transition effects, unlike in default Xamarin Forms Navigation Stack. This is a great feature that is provided by this solution hence a lot of developers were having issues with this restriction of Xamarin Forms since long time back. 🙂

2. PushPopupAsync()

Also it is important to mention that, when using Popup pages of Rg.Plugins.Popup  we should always use the Navigation.PushPopupAsync() extension if we want to preserve the Transparency and Custom Page transition features. Meanwhile using the PopupNavigation.PopAsync() to remove the pages from the stack while maintaining transition effects. 😀

3. PushPopupAsync()

We are all aware of how on Android run time, Xamarin Forms uses a Single Activity to populate the Pages of our app. And usually when we add a Modal Page, it gets populated on top of the Single Activity the app is running on. But in this Library it uses a separate Android Dialog View which doesn’t use the Activity Stack, instead it draws itself over the Activity, (blocking the whole Activity content) such as in AndHUD library. So that’s something to keep in mind if you wonder why you couldn’t Push a Page on top of this popup page. 😉

Finally kudos to the developers of Rg.Plugins.Popup plugin for Xamarin Forms!

So I gave a Tech Talk at Dot Net Developers Meetup, Singapore hosted by Microsoft…

Yeei! 😀 I got an awesome opportunity present a tech talk at Dot Net Developers Meetup in Singapore which was hosted by Microsoft. This happened to be my first ever Presentation on Xamarin, and yeah it was totally awesome. A great enthusiastic crowd and everything went pretty well.. 🙂

Thank you so much for the Organizers and Microsoft for this incredible opportunity, and I’m truly humbled by it.

There I spoke about Xamarin and Xamarin Forms, Xamarin UI Rendering process, Overriding this process through Custom Renderers, and important facts to keep in mind when implementing Custom Renderers in Xamarin Forms.

So I thought of putting out a small article on the Summary of this tech talk on my blog. 😀

Xamarin Forms Custom Renderers for the Rescue…

Here’s the slideshow I used during this talk…

Xamarin is…

Xamarin is truly a great platform. It let’s you create mobile applications using C# dot net having full Native Performance as well as Looks and Feels of each Native Platform.

Xamarin Forms Custom Renderers for the Rescue.004

As you can see in the diagram, thanks to Xamarin now we can maintain the same code base across all three mobile platforms, having the individual native UI implementation, which allows us to maintain up to about 70% percent shared codebase. So yeah its all Great.

Xamarin Forms is…

Xamarin Forms, in one single word, is awesome! Its more like the cross platform extension of Xamarin this is the component which brings to life of the concept, Write once, Run Everywhere, and not Suck allowing us to share the UI code layer among three platforms. So you no longer need to implement the UI separately for each platform.

Xamarin Forms Custom Renderers for the Rescue.005

Xamarin and Xamarin Forms ?

Some people are confused about these differentiation between Xamarin and Xamarin Forms, let me put it this way…

Xamarin Forms Custom Renderers for the Rescue.006

Xamarin Forms is more like the true cross platform extention of Xamarin. Where as Xamarin Forms provides us a unified UI Layer which has all the common UI controls (Layouts, Labels, TextBoxes, Buttons, etc…) of all three mobile platforms, with almost every single common property of those controls.

Still Confused ? Let me explain…

Xamarin Forms Custom Renderers for the Rescue.007

In your left hand side you can see the Native Xamarin architecture where you share the back-end code base, but you have to implement the UI separately for each platoform, allowing us to share upto 70-80% of code base.

Where as in Xamarin Forms you can share almost upto 100% of the code base across all three platforms with the Shared UI Layer.

A little Story about a fresh Xamarin Forms developer…

There’s this developer who started developing an application with Xamarin forms, where he’s given all the UI sketches and so on.

Xamarin Forms Custom Renderers for the Rescue.008

So he start off with default nice and simple controls in Xamarin Forms and manages to implement the basic UI design of the app. Then he slowly gets into complex UI designs implementations…

So he starts going through all the available properties in these Xamarin Forms Controls, and begins to wonder where are all the properties that he needs to be using in order to customize the app accordingly to the complex design.

So he looks up and down, here and there, wondering where did all the properties go?

Oh boy, he’s in trouble, isn’t he… He realise Xamarin Forms UI controls has limited set of properties for customization, and its very hard to do complex customization in these controls.

Any Solutions ?

Any solutions ? Well he could always go back to native development, but its late for it now, and it’ll put him through a lot of trouble for sure, having to implement in three platforms.

Now that’s where Xamarin Forms Custom Renderers comes in for the rescue, let me explain.

Xamarin Forms Custom Renderers for the Rescue.010

Xamarin Forms UI Rendering process…

Each and every UI Control in Xamarin Forms has it’s own Native Renderer which renders and maps its Properties and Behaviours to the Native Control level.

So yeah behold the Magic of Xamarin Forms, this happens accordingly to the Native Platforms. This is why we get the Native look and feel and performance with Xamarin Forms.

Xamarin Forms Custom Renderers for the Rescue.011

Take a look at the Diagram here it shows how the default texbox UI Control of Xamarin Forms, which is called “Entry” control gets rendered down to the Native level through the Renderers. Now focus down through the iOS rendering, where the Entry control gets rendered down to the native UITextField control. And on Android and Windows Phone, EditText and UserControl respectively.

Overriding this Rendering Process ?

Xamarin has allowed us to access this Rendering process, which in return allows us to Override this default process and use it for our own requirements.

Xamarin Forms Custom Renderers for the Rescue.012

So by accessing this process we can customize all kinds of properties and behaviours of the Xamarin Forms controls, in each platform according to our needs.

Xamarin Forms Custom Renderers…

So in order to access this rendering process we need to create Custom Renderers of our own by sub classing the base Renderers Xamarin provides. Thereby it allows us to access and modify the native level properties and behaviours of the Xamarin Forms Controls.

Xamarin Forms Custom Renderers for the Rescue.013

Take a look at the Diagram above, that’s how Custom Renderers gets involved in the Rendering process, where as the Xamarin Forms Entry control goes through the Custom Renderer and down to the base renderer, where we control and modify its properties and behaviours in our Custom Renderer as we need.

How to create Xamarin Forms Custom Renderers ?

Just 3 simple steps…

  1. First you create a Custom Control by subclassing the default Xamarin Forms Control that you need to create a Custom Renderer for.
  2. Second you consume that subclassed Custom Control in your Xamarin Forms application.
  3. Thirdly and finally, you implement the Custom Renderer in the Native levels project.

Yeah how hard could it be, just three simple steps! 😉

Here’s a Simple Custom Renderer Demo on the house…

Check out the live demo Custom Renderer I implemented during this presentation on my Github from below, https://github.com/UdaraAlwis/XFCircleCornersButtonControlDemo

Important facts to consider WHEN implementing Custom Renderers…

So here are some important facts to keep in mind when you implement Custom Renderers in Xamarin Forms, so that you get a good understanding about how to implement a custom renderer and what to keep in mind…

1. Always Export your Custom Renderers…

Whenever you create a custom renderer you need to Export it and register it, otherwise Xamarin would not recognise your Custom Renderer and it will go ahead with the default base class Renderer for your Custom Control.

Capture

2. Overriding the OnElementChanged Method…

Whenever a Custom Renderer is being execute, the first method it fires is the OnElementChanged() method.

This method gets called when the Rendering process starts for the custom control, which allows us the opportunity to to tap into the native properties and behaviours and modify them as we wish by overriding this method.

Also something to keep in mind this method consumes an important parameter, ElementChangedEventArgs which contains two important Properties.

  1. The OldElement property represents the Xamarin Forms level Control this renderer was attached to (previously attached to) and
  2. The NewElement property represents the Xamarin Forms level Control this renderer is currently attached to, its more of a reference.

So if you are using any Event Handlers in your Custom Renderer, you have to keep an eye out for these two properties in order to Subscribe and Unsubscribe accordingly to prevent memory leaks.

Capture1

3. Control vs Element Property…

If you think about it, Custom Renderer is more like a middle guy, in between Xamarin Forms level Control and the Native level Control, where as it’s got hooks for both levels.

So those hooks are represented by these two important properties, Control and Element.

Element property, it holds a reference to the Xamarin.Forms control that’s being rendered, so you could use this property to access anything on the Xamarin Forms level of the custom control, such as Text, WidthRequest, HeightRequest and so on.

Control property holds a reference to the Native Control being used of the Custom Control. So using this property you can straight away add your native customisations and behaviours to the Rendering Control.

3. Overriding the whole Native Control ?

What if you want to get rid of the default Native Control associated with your Custom Renderer ? Create your own Native Control and use it for your Custom Control ?

As an example You need to have a TextBox with an underneath shadow, in iOS you can’t do this with the default native UITextView, so one way to do it is by adding another UIView along with the UITextView, where as you merge two native views together to form one View.

So for instances like that, you could use the SetNativeControl() method, and pass in your custom native view, which will get rid of the default native view and override it with your custom native view.

But you have to keep in mind something very important, hence you are flushing away the default native control, you have to handle all the Behaviours (Events) of your own Native Control manually by yourself and map it back and forth with the Xamarin Forms level.

4. Creating your own Base Renderer…

For every Xamarin Forms Control, there is a Base Renderer, that maps it to the Native Level and we use those Base Renderers all the time such as Button Renderer, Label Renderer and so on.

Now what if you wanted to create your own Base Renderer ? Let’s say you are creating a total complex Custom Control by yourself, and you need to have your own Renderer for it?

YES! it is possible, you just simply have to derive your Base Renderer from the generic ViewRenderer<?,?> where as you have to pass in your Custom Renderer type name and the associating Native Control type name for the renderer.

Well actually Xamarin doesn’t really recommend this, there some instance that you need to move towards this approach.

Let me Share some Wisdom…

Xamarin Forms Custom Renderers for the Rescue.022

Here’s something interesting I really want share with your all is that, Xamarin doesn’t really require in depth Mobile Development knowledge but it is very beneficial to have some, specially in scenarios like these Custom Renderer implementation. The more you are aware of the Native development, the more advantages for you.

So if you are planning to move towards Xamarin mobile development, I would suggest you take a little look at native development as well… Which will prepare you better for your Xamarin Mobile Development journey.

Important facts to consider BEFORE implementing Custom Renderers…

Earlier I mentioned about the facts that you need to keep in mind when you implement Custom Renderers, now let’s see what are the facts you need to focus BEFORE you decide to implement Custom Renderers in your application.

 

1. Think twice…

You need to think twice before you move on towards Custom Renderer implementation for your Application. Once you get familiar with Custom Renderer implementation, you get very tempted to go for custom renderers all the time even for the simplest requirement, but trust me it is not a good practice at all.

Why I say this is because, and untold truth about Custom Renderers is that, they are a little process intensive.

Therefore it’s wise to first of all explore all the possible solutions you could come up with from Xamarin Forms level it self to solve your requirement. So do not over-use Custom Renderers just because of the ease of development.

You could also try out other alternatives such as,

  1. Xamarin Forms Controls sub-classing and forming Custom Control (by merging multiple Controls to create a new Control).
  2. Xamarin Forms Effects (which is almost like Custom Renderers but simplified).

 

2. Re-usability…

Whenever you decide to implement a Custom Renderer You need to pay attention to the reusability of it. Make sure to implement it in a way its reusable as much as possible.

When ever you implement Custom Renderers, don’t only focus on the current implementation, think ahead and implement all the possible needs in one go, without implementing custom renderers for every single need from one type of control.

Since Custom renderers are process intensive it very important to focus on reusability.

3. Mapping of Xamarin Forms -> Native Level…

Last but not least before you implement your Custom Renderer always make sure to take a look down through your Rendering Hierarchy…

Xamarin Forms Custom Renderers for the Rescue.026

Look at the available Properties and Behaviours down to the Native control and see whether it actually fulfils your requirements, in all three platforms (Android, iOS, Windows Phone). That way you will have a better idea on how to implement the Custom renderer more efficiently.

Conclusion…

Xamarin Forms Custom Renderers for the Rescue.028

Custom Renderers plays an extremely important role in Xamarin Forms development. In my opinion it’s more like the Magic behind the whole Xamarin Forms Awesomeness.

Don’t be scared of Custom Renderer’s because they are here for your rescue.

Also finally make sure to keep in mind all the important tid bits I discussed today, so it will help you implement custom renderers more efficiently and effectively. 🙂

AAAANND THAT BROUGHT US TO THE END OF THE PRESENTATION! Hope this was helpful for anyone missed this session and keep in touch everyone! 😀

Once again Thanks for the Organisers for organising this event and Microsoft for hosting. As well as the enthusiastic crowd. 🙂

– Udara Alwis
CODENAME: [ÇøŋfuzëРSøurcëÇødë]

https://www.linkedin.com/in/udaraalwis

https://www.facebook.com/confuzed.sourcecode