Category Archives: Xamarin Android

Advanced Segmented Button Control in pure Xamarin.Forms!

Welcome to the Part 2 of my Segmented Button Control in Xamarin.Forms, in which this time we’re going to take it to the advanced level and make it even cooler and more awesome!

If you missed the Part 1 of this article, please go on there and give it a read,A Segmented Button Control in pure Xamarin.Forms! Specially since this article is going to be heavily linked to it. So there we looked into how to create a simple yet awesome Segmeneted Control in pure Xamarin.Forms without any custom renderers or native code. And in this article we’ll be looking into how to make it even more awesome with a bit more advanced implementation. Keep in mind I’m not going to explain all the concept bits which I had discussed in the Part 1 but I will be mentioning about them to be referred to. So let’s begin!

Welcome to Part 2!

A Segmented Control, or as some call it Grouped Button Control, or Tabbed Button Control or some even call the Rocker Control, is what I’m gonna share with yol today, built 100% from Xamarin.Forms! Specially in this Part 2 article, we’re including the ability to add Segmented Buttons on the go and change the Color themes at run time, making it full dynamic.

We’re going to rely on the same basic concept’s we talked about in Part 1 article, only the implementation and handling of the behavior to include the new features are going to be different in this.

Sneak Peak

Here’s a sneak peak of what I built for Part 2 article…

iOS:

  

Android:

   

that’s what we gonna build yo! 😉

FULLY DYNAMIC | ADDING/REMOVE TABS | SWITCHING COLORS  | SWITCHING TAB

Look at that awesomeness eh! Hold up, we’re about to get started…

This whole awesome project is hosted up in my Github repo:  https://github.com/UdaraAlwis/XFSegmentedControl 

Recipe time…

So this is basically going to be the same concepts we’ve used in the Part 1 therefore I’m not going to be repeating the same stuff I had explained in details in Part 1 Article. Please give a read to the “Recipe time…” section in it.

In here we’re going to separate the Tab Button element from the SegmentedControl, so that we can dynamically add the Tab Buttons dynamically at run time. We’re going to maintain an IEnumerable list in the SegmentedControl.

Also unlike last time we’re going to implement and properly handle the Color properties and SelectedTab index property, so that all those properties cab be changed dynamically as we wish.

Well that’s pretty much it, with a bit more details to be gotten into later.

Coding time…

So let’s begin with our separated TabButton element, which you could also identify as a “Segmented Button” element of our Segmented Button Control. This element includes with a simple Button, Label and BoxView inside of a Grid view, that makes it up just like the last article implementation.

<?xml version="1.0" encoding="UTF-8" ?>
<Grid
   x:Class="XFSegmentedControl.Advanced.Controls.TabButton"
   xmlns="http://xamarin.com/schemas/2014/forms"
   xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
   IsClippedToBounds="True">
   <Button
      x:Name="TabButtonView"
      Margin="-2,-3,-2,0"
      Clicked="TabButton_OnClicked" />
   <Label
      x:Name="TabLabelView"
      FontAttributes="Bold"
      FontSize="Medium"
      HorizontalOptions="CenterAndExpand"
      InputTransparent="True"
      Text="Tab Text"
      VerticalOptions="CenterAndExpand" />
   <!--  Horizontal indicator for Android  -->
   <BoxView
      x:Name="HorizontalIndicator"
      HeightRequest="2"
      InputTransparent="True"
      IsVisible="False"
      VerticalOptions="End" />
   <!--  Vertical separator for iOS  -->
   <BoxView
      x:Name="VerticalSeparator"
      HorizontalOptions="Start"
      InputTransparent="True"
      IsVisible="False"
      VerticalOptions="FillAndExpand"
      WidthRequest="1" />
</Grid>

 

There’s the XAML with the basic Button and Label which handles the Text and click event of the TabButton and then the two BoxViews that we’re going to use to decorate for Android and iOS platform specific look and feel.

Check out the full source code here: TabButton.xaml

Next let’s take a look at the code behind awesomeness of our TabButton control.

public partial class TabButton : Grid
{
    public event EventHandler<EventArgs> TabButtonClicked;
    public string TabText { get; private set; }
    public int TabIndex { get; private set; }
    public Color PrimaryColor { get; private set; }
    public Color SecondaryColor { get; private set; }

    public TabButton(string tabText, int tabIndex, Color 
       primaryColor, Color secondaryColor, 
       bool isSelectedByDefault)
    {
        InitializeComponent ();

        // Set up default values from params
        ...
       
        // Set up default color values
        SetUpColorScheme();

        // set up selected status
        if (isSelectedByDefault)
            TabButtonView.SendClicked();
    }

    private void SetUpColorScheme()
    ...

    private void TabButton_OnClicked(
                  object sender, EventArgs e)
    {
        SetSelectedTabState();

        SendTabButtonClicked();
    }

    private void SetSelectedTabState()
    ...
    private void SetUnselectedTabState()
    ...

    /// <summary>
    /// Update the Tab Button status Selected/Unselected
    /// </summary>
    /// <param name="selectedTabIndex"></param>
    public void UpdateTabButtonState(int selectedTabIndex)
    {
        if (selectedTabIndex != TabIndex)
            SetUnselectedTabState();
        else
            SetSelectedTabState();
    }

    /// <summary>
    /// Update the Color status of the Tab Button
    /// </summary>
    /// <param name="primaryColor"></param>
    /// <param name="secondaryColor"></param>
    public void UpdateTabButtonColors(
           Color primaryColor, Color secondaryColor)
    ...
}

 

So in the code behind we’re handling all the functionality and look and feel appearance of the Tab Button segment or element. In the constructor itself we’re passing in the Color properties, Text, Index of the current Tab Button and the selected Status of this Tab Button, then we’re assigning them to the visual elements of the TabButton appropriately, whilst, storing the important values locally for later use.

The SetUpColorScheme() applies to color properties of the element, and I’ve moved that to a separate methods because we’re going to be allowing the user to update the color properties on the go. If you had noticed how we’re subscribing to the TabButton_OnClicked in our XAML code, there we’re handling it by calling the SetSelectedTabState() method and SendTabButtonClicked(), which will update the appearance of the current TabButton to the Selected State and then invoke the EventHandler for whichever the entity that’s subscribed to it from the outside.

Then the an important Public method, UpdateTabButtonState() which allows an external source to update the current Visual-Selected State of the TabButton. You can see how it calls upon the SetSelectedTabState() and SetUnselectedTabState() based on the passed in parameter selectedTabIndex.

Last but not least the UpdateTabButtonColors() allows us to update the Color theme of the TabButton on the go from an external source.

Check out the full source code here: TabButton.xaml.cs

Next we’re going to create the Parent custom control elements that’s going to be holding all of the TabButton elements together. Let’s call it AdvSegmentedControl, thus interpreting Advanced Segmented Control! 😉

<?xml version="1.0" encoding="UTF-8" ?>
<ContentView
   x:Class="XFSegmentedControl.Advanced.Controls.AdvSegmentedControl"
   xmlns="http://xamarin.com/schemas/2014/forms"
   xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
   xmlns:system="clr-namespace:System;assembly=netstandard">
   <ContentView.Content>
      <Frame
         x:Name="FrameView"
         Padding="0"
         IsClippedToBounds="True">
         <!--  Platform specific customization values for the border  -->
         <Frame.HasShadow>
            <OnPlatform x:TypeArguments="system:Boolean">
               <On Platform="Android" Value="False" />
               <On Platform="iOS" Value="True" />
            </OnPlatform>
         </Frame.HasShadow>
         <Frame.CornerRadius>
            <OnPlatform x:TypeArguments="system:Single">
               <On Platform="Android" Value="0" />
               <On Platform="iOS" Value="5" />
            </OnPlatform>
         </Frame.CornerRadius>
         <Frame.HeightRequest>
            <OnPlatform x:TypeArguments="system:Double">
               <On Platform="Android" Value="50" />
               <On Platform="iOS" Value="35" />
            </OnPlatform>
         </Frame.HeightRequest>
         <!--  Platform specific customization values for the border  -->

         <!--  Holder of the Child Tab buttons  -->
         <Grid x:Name="TabButtonHolder" ColumnSpacing="0" />

      </Frame>
   </ContentView.Content>
</ContentView>

 

That’s pretty much it, I’m sure you’re already familiar with the styling of the Frame element from my previous post and the Grid named as TabButtonHolder is what we’re going to be using in the code behind to maintain the Child elements of TabButtons.

Next comes the Code behind of AdvSegmentedControl 😀

public partial class AdvSegmentedControl : ContentView
{
   BindableProperty PrimaryColorProperty
   ...
   BindableProperty SecondaryColorProperty
   ...
   BindableProperty SelectedTabIndexProperty
   ...
   BindableProperty TabButtonsSourceProperty
   ...
   static void OnTabButtonsPropertyChanged
   (BindableObject bindable, object oldValue, object newValue)
   {
      if (newValue != null)
      {
         // clear up existing childrens
         ((AdvSegmentedControl)bindable)
                    .TabButtonHolder.Children?.Clear();

         int index = 0;
         foreach (var item in (IEnumerable) newValue)
         {
            // create new Tab Button
            var newTab = new TabButton(
            item.ToString(),
            index, 
            ((AdvSegmentedControl)bindable).PrimaryColor, 
            ((AdvSegmentedControl)bindable).SecondaryColor,
            (index == ((AdvSegmentedControl)bindable)
                                       .SelectedTabIndex));

            newTab.TabButtonClicked += (sender, args) =>
            {
               ((AdvSegmentedControl)bindable).SelectedTabIndex
                  = ((TabButton)sender).TabIndex;
            };
            
            Grid.SetColumn(newTab, index++);

            // add the new tab to TabButtonHolder
            ((AdvSegmentedControl)bindable).
                  TabButtonHolder.Children.Add(newTab);
         }
      }
      else
      {
         // clear up existing childrens
         ((AdvSegmentedControl)bindable).
                  TabButtonHolder.Children?.Clear();
      }
   }

   public AdvSegmentedControl ()
   ...
}

 

So its all similar to the previous article’s implementation, all the properties and handling of the behavior, except now we’re maintaining a list of TabButton references in TabButtonsSource property, which is a list of strings that we could use as names for the Tabs, instead of having a hard coded static Tab buttons in our previous implementation. And we’re subscribing to it to handle the adding and removal of the Tabs or Segmented Buttons at run time on demand.

Inside the loop we’re creating new instances of TabButton and passing in the relevant properties that are assigned, then subscribing to the TabButtonClicked event, ending each loop cycle by adding the TabButton instance to the TabButtonHolder Grid.

Check out the full source code here: AdvSegmentedControl.xaml.cs

Now that’s pretty much it. Let’s consume this awesomeness of AdvSegmentedControl! 😉

Time for consumption…

Now that we are done with our awesome AdvSegmentedControl, next let’s consume it in anywhere we wish in our Xamarin.Forms app!

<controls:AdvSegmentedControl
    x:Name="segmentedControl"
    PrimaryColor="CornflowerBlue"
    SecondaryColor="White"
    SelectedTabIndex="2"       
    SelectedTabIndexChanged="OnSelectedTabIndexChanged">
    <controls:AdvSegmentedControl.Padding>
        <OnPlatform x:TypeArguments="Thickness">
            <On Platform="Android" Value="0" />
            <On Platform="iOS" Value="10,0,10,10" />
        </OnPlatform>
    </controls:AdvSegmentedControl.Padding>
    <controls:AdvSegmentedControl.TabButtonsSource>
        <x:Array Type="{x:Type x:String}">
            <x:String>Monkeys</x:String>
            <x:String>Minions</x:String>
            <x:String>Penguins</x:String>
            <x:String>Foxes</x:String>
        </x:Array>
    </controls:AdvSegmentedControl.TabButtonsSource>
</controls:AdvSegmentedControl>

 

There you go a simple demonstration of how to consume this awesomeness! We’re using PrimaryColor, SecondaryColor properties to set the color theme and the SelectedTabIndex property allowing you to set the default selected Tab on appearing. We have added a list of Strings to our TabButtonsSource to populate the Tab Buttons or Segmented Buttons as we wish. Also we’re subscribing to the SelectedTabIndexChanged event to react to the changes of the selected Tab by the user (you know load some view or execute whatever the action you wish). Keeping in mind all those properties can be changed at run time and will reflect visually! how awesome is that! 😀

Let’s fire it up and see it in action! 😉

Fire it up!

Here we go…

  

There we go baby! iOS and Android running side by side…

Something more awesome…

So just to show how powerful my AdvSegmentedControl is, I cooked up bit of a cool demo right here. Oh I hope you still remember that little sneak peak I showed you at the beginning of the article! 😉

Let’s start off with iOS:

 

And Android:

 

TADAAA! 😀

FULLY DYNAMIC | ADDING/REMOVE TABS | SWITCHING COLORS  | SWITCHING TAB

Check out the awesome demo code went into this from here: MoreDemoPage.xaml

Well your imagination is the limit fellas! 😀

This whole awesome project is hosted up in my Github repo:  https://github.com/UdaraAlwis/XFSegmentedControl 

Cheers! 😀 Keep on going my fellow devs!

Spread the love…

Advertisements

Simple Segmented Button Control in pure Xamarin.Forms!

A Segmented Control, or as some call it Grouped Button Control, or Tabbed Button Control or some even call the Rocker Control, is what I’m gonna share with yol today, built 100% from Xamarin.Forms!

Yeah such a platform specific UI element, right out of Xamarin.Forms without a single line of native code, how’s that even? Well if you’ve been following my blog for a while, you know that I’m all about pushing them limits of any given platform and achieve the impossibru! 😉

Whut whut in Xamarin.Forms?

So there’s many different interpretations of this UI elements and also different use cases. Specifically you can see this in native Tabbed Page views in both Android and iOS. And in native platforms they actually have their own Segmented button controls, that allows you to have a set of buttons in a single segment, that allows you to have a selected state, which will let you perform a certain operation, change a value or load a certain View to another element.

So when it comes to Xamarin.Forms, there’s no out of the box UI element that provides this view, unless you use Xamarin.Forms TappedPage control, in which case is impractical if you’re not in need of a Tabbed Page, or worse case in a Content element area where you absolutely can’t use a Page element.

Le Solucioano!

So here’s my solution for this, a Segmented Control in pure Xamarin.Forms, that allows you to have the same exact look and feel and behavior of a native Segmented Control, or a Tabbed Button Control or a Rocker Control or whatever. Lol

Specially no custom renderers, no native code or whatever, just simple and pure Xamarin.Forms! 😉

Sneak Peak

Here’s a sneak peak of what I built, on iOS..

And on Android..

Look at the eh, just like a native control with all the looks and feels and behaviours…

This whole awesome project is hosted up in my Github repo : https://github.com/UdaraAlwis/XFSegmentedControl 

Recipe time…

Buckle up, contains a whole bunch of me hacking around pushing the limits of Xamarin.Forms to achieve some impossibru! 😉

So first thing, we need to keep in mind the aspect of having the same look and feel of a native Segmented control, in aspect of both Android and iOS, therefore we’re going to be using a lot of platform specific properties in XAML and code behind.

We are going to have two Buttons inside a Layout, to emulate the two segmented Buttons. The layout is going to be a Xamarin.Forms Frame, since it has the property CornerRadius, which is vital to gain the curved corners appearance for iOS, and Border property, which we can use to draw the border around the element for iOS. As of Android we can disregard both of those properties. Also don’t forget about the IsClippedToBounds property which all the Layout elements has in Xamarin.Forms, allowing you to crop out of bounds elements inside the layout, which will allow us to have that curved corners in iOS without the button borders popping out of it.

So you might say as of the Button we could use a Label or something and then use a Tap Gesture to handle the click event. Nope! I like the perfection of whatever I’m building! 😉 Therefore we’re going to use actual Xamarin.Forms Button control, now hold on…

Now speaking of the Buttons, we can’t use Buttons with text inside, since the default behaviour of a button restricts the visibility of Text inside it. Therefore we’re going to use a little hack I have always used, that is placing one element over another inside a Grid view. So we are going to use a Button without text inside of it, and then a Label on top of it that represents the Text of the Segmented Button. So you’re probably worries about the Button click behaviour since we’re laying out a Label on top of it, but hello don’t worry, that’s where InputTransparent comes into rescue, passing down the touch even down to the Button straight away! So on selection of the Button we shall do the necessary changes to show the IsSelected status.

We are going to assign name identifiers to our elements in this control to handle some of the code behind magic as well, in case you wondered when you see the code! 😀

Also not to mention that we’re going to maintain properties inside the custom control, like Colors, Text, Selected Button Index properties and also an EventHandler to inform the changes of the Segment button selection.

Well that’s pretty much it, with a bit more details to be gotten into later.

XAML time…

We’re going to create a custom control elements that’s going to be independent and reusable anywhere in the project. Let’s call it SimSegmentedControl, thus denoting “Simple Segmented Control”!

<?xml version="1.0" encoding="UTF-8" ?>
<ContentView
    x:Class="XFSegmentedControl.Simple.Controls.SimegmentedControl"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:system="clr-namespace:System;assembly=netstandard">
    <ContentView.Content>
	
	<!--  Rest of content goes here (Next code snippet) -->
	
    </ContentView.Content>
</ContentView>

 

Now let’s get into the inside elements of our SimSegmentedControl, which is basically the Frame Layout that I explained before.

<Frame
    x:Name="FrameView"
    Padding="0"
    IsClippedToBounds="True">
    <!--  Platform specific customization values for the border  -->
    <Frame.HasShadow>
        <OnPlatform x:TypeArguments="system:Boolean">
            <On Platform="Android" Value="False" />
            <On Platform="iOS" Value="True" />
        </OnPlatform>
    </Frame.HasShadow>
    <Frame.CornerRadius>
        <OnPlatform x:TypeArguments="system:Single">
            <On Platform="Android" Value="0" />
            <On Platform="iOS" Value="5" />
        </OnPlatform>
    </Frame.CornerRadius>
    <Frame.HeightRequest>
        <OnPlatform x:TypeArguments="system:Double">
            <On Platform="Android" Value="50" />
            <On Platform="iOS" Value="35" />
        </OnPlatform>
    </Frame.HeightRequest>
    <!--  Platform specific customization values for the border  -->

    
    <!--  Segmented Buttons go in here (Next code snippet)  -->
    
</Frame>

 

As you can see I have added a whole bunch of platform specific customization values for Android and iOS to achieve the design we’re targeting for, such as CornerRadius and Height.

Then let’s add our Segmented Button elements, just to make it easier let’s identify each of them as “Tab Button” element.

<Grid ColumnSpacing="0">

    <!--  Tab button 1  -->
    <Grid Grid.Column="0" IsClippedToBounds="True">
        <Button
            x:Name="Tab1ButtonView"
            Margin="-2,-3,-2,0"
            Clicked="Tab1Button_OnClicked" />
        <Label
            x:Name="Tab1LabelView"
            FontAttributes="Bold"
            FontSize="Medium"
            HorizontalOptions="CenterAndExpand"
            InputTransparent="True"
            Text="Tab 1"
            VerticalOptions="CenterAndExpand" />
        <BoxView
            x:Name="Tab1BoxView"
            HeightRequest="2"
            InputTransparent="True"
            IsVisible="False"
            VerticalOptions="End" />
    </Grid>
    <!--  Tab button 1  -->

    <!--  Tab button 2  -->
    <Grid Grid.Column="1" IsClippedToBounds="True">
        <Button
            x:Name="Tab2ButtonView"
            Margin="-2,-3,-2,0"
            Clicked="Tab2Button_OnClicked" />
        <Label
            x:Name="Tab2LabelView"
            FontAttributes="Bold"
            FontSize="Medium"
            HorizontalOptions="CenterAndExpand"
            InputTransparent="True"
            Text="Tab 2"
            VerticalOptions="CenterAndExpand" />
        <BoxView
            x:Name="Tab2BoxView"
            HeightRequest="2"
            InputTransparent="True"
            IsVisible="False"
            VerticalOptions="End" />
    </Grid>
    <!--  Tab button 2  -->

    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*" />
        <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
</Grid>

 

Voila! behold the two button elements, with all the platform specific customizations, just like how I explained before, Label on top of a Button inside a Grid layout. Also you may have noticed the Margin property that I have used with “-2,-3,-2,0”, which is to stretch out the empty border line of the buttons out of the Grid so it crops out with the IsClippedToBounds property.

And the BoxView is to emulate the bottom line we have in Android look and feel of the Segmented Control.

Code-behind time…

Now this is where we’re basically going to handle all the action in our SegmentedControl!

So I’m not going to spoon feed the whole code in this blog post, since its going to be a pretty lengthy one, so I’ll be cutting out most of the repetitive code which you can easily figure out yourself or just check out on my github repo where I have committed this whole project code.

So like I explained at beginning we’re going to have a bunch of properties that are going to handle all the customization values such as Color, Text, SelectedIndex, EventHandler and so on. And then apply a whole bunch of code behind customization for platform specific look and feels, along with the handling of Segment button click event behavior.

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SimSegmentedControl : ContentView
{
    public static readonly BindableProperty PrimaryColorProperty
        = BindableProperty.Create(
            nameof(PrimaryColor),
            typeof(Color),
            typeof(SimSegmentedControl),
            Color.CornflowerBlue);

    public Color PrimaryColor
    {
        get { return (Color)GetValue(PrimaryColorProperty); }
        set { SetValue(PrimaryColorProperty, value); }
    }

    // SecondaryColorProperty

    // Tab1TextProperty

    // Tab2TextProperty

    // SelectedTabIndexProperty
    
    public event EventHandler<SelectedTabIndexEventArgs> SelectedTabIndexChanged;

    public SimSegmentedControl()
    {
        InitializeComponent();
    }

    /// <summary>
    /// load up the customizations and applying
    /// properties when the element has rendered
    /// </summary>
    protected override void OnParentSet()
    {
        base.OnParentSet();
        
        // Setting up platform specific properties for Android and iOS
        if (Device.RuntimePlatform == Device.Android)
        {
            Tab1LabelView.FontSize
                = Device.GetNamedSize(NamedSize.Medium, Tab1LabelView);
            Tab2LabelView.FontSize
                = Device.GetNamedSize(NamedSize.Medium, Tab1LabelView);

            Tab1ButtonView.BackgroundColor = PrimaryColor;
            Tab2ButtonView.BackgroundColor = PrimaryColor;

            Tab1BoxView.Color =
            Tab2BoxView.Color =
            Tab1LabelView.TextColor =
            Tab2LabelView.TextColor = SecondaryColor;
        }
        else if (Device.RuntimePlatform == Device.iOS)
        {
            Tab1LabelView.FontSize
                = Device.GetNamedSize(NamedSize.Small, Tab1LabelView);
            Tab2LabelView.FontSize
                = Device.GetNamedSize(NamedSize.Small, Tab1LabelView);

            Tab1ButtonView.BackgroundColor =
            Tab2ButtonView.BackgroundColor = PrimaryColor;

            FrameView.BorderColor =
            Tab1LabelView.TextColor =
            Tab2LabelView.TextColor = SecondaryColor;
        }

        Tab1LabelView.Text = Tab1Text;
        Tab2LabelView.Text = Tab2Text;

        // setting up default values
        SelectTab1();
        SelectedTabIndex = 1;
        SendSelectedTabIndexChangedEvent();
    }

    private void Tab1Button_OnClicked(object sender, EventArgs e)
    {
        SelectTab1();
        SelectedTabIndex = 1;
        SendSelectedTabIndexChangedEvent();
    }

    private void Tab2Button_OnClicked(object sender, EventArgs e)
    {
        SelectTab2();
        SelectedTabIndex = 2;
        SendSelectedTabIndexChangedEvent();
    }
    
    // SelectTab1()
    
    // SelectTab2()
    
    // SendSelectedTabIndexChangedEvent()
}

 

So we PrimaryColor and SecondaryColor which handles the two main colors that is styling our SimSegmentedControl, which is exactly how it being used in native version of this control as well, just two simple Colors styling the whole element.

Then Tab1Text and Tab2Text property to handle the Text that needs to be displayed in the Segmented buttons.

As you can see OnParentSet (this is when the View is rendered in memory and just about to be displayed on the Page) we’re applying all the platform specific customization for the elements in our SimSegmentedControl. Then you can see we’re setting the Tab1 and Tab2 text properties to our Labels, which is not actually good practice, but I was too lazy to add that in the PropertyChangedEvent handler of those respective bindable properties. After that at the end you can see we’re setting the default values.

Also the SelectedTabIndexChanged EventHandler is there to notify any outside element who wants to be aware of the selected Tab in our SimSegmentedControl, so they can perform whatever the action based on it.

Then let me get into the SelectTab1(), SelectTab2() and SendSelectedTabIndexChangedEvent methods.

private void SelectTab1()
{
    // set up platform specific
    // properties for SelectTab1 event
    if (Device.RuntimePlatform == Device.Android)
    {
        Tab1BoxView.IsVisible = true;
        Tab2BoxView.IsVisible = false;
    }
    else if (Device.RuntimePlatform == Device.iOS)
    {
        Tab1ButtonView.BackgroundColor = SecondaryColor;
        Tab2ButtonView.BackgroundColor = PrimaryColor;

        Tab1LabelView.TextColor = PrimaryColor;
        Tab2LabelView.TextColor = SecondaryColor;
    }
}

private void SelectTab2()
{
    // set up platform specific
    // properties for SelectTab2 event
    if (Device.RuntimePlatform == Device.Android)
    {
        Tab1BoxView.IsVisible = false;
        Tab2BoxView.IsVisible = true;
    }
    else if (Device.RuntimePlatform == Device.iOS)
    {
        Tab1ButtonView.BackgroundColor = PrimaryColor;
        Tab2ButtonView.BackgroundColor = SecondaryColor;

        Tab1LabelView.TextColor = SecondaryColor;
        Tab2LabelView.TextColor = PrimaryColor;
    }
}

/// <summary>
/// Invoke the SelectedTabIndexChanged event
/// for whoever has subscribed so they can
/// use it for any reative action
/// </summary>
private void SendSelectedTabIndexChangedEvent()
{
    var eventArgs = new SelectedTabIndexEventArgs();
    eventArgs.SelectedTabIndex = SelectedTabIndex;

    SelectedTabIndexChanged?.Invoke(this, eventArgs);
}

--------------

public class SelectedTabIndexEventArgs : EventArgs
{
    public int SelectedTabIndex { get; set; }
}

 

So there you can see in SelectTab1() we’re setting up the necessary customization for the Selected state of our Segmented Button for both Android and iOS, such as the BackgroundColor, TextColor and whatnot. And then in SelectTab2() we’re doing the exact opposite customization, Button 1 -> Unselected and Button 2 -> Selected appearance.

Then in the SendSelectedTabIndexChangedEvent we’re basically broadcasting the selected Tab index of our SimSegmentedControl with the SelectedTabIndex property value.

Time to consume!

Let’s use this awesome SimSegmentedControl in our Page shall we?!!! 😀

<local:SimSegmentedControl
	x:Name="SegmentedControlView"
	PrimaryColor="CornflowerBlue"
	SecondaryColor="White"
	SelectedTabIndexChanged="SegmentedControlView_SelectedTabIndexChanged"
	Tab1Text="Monkeys"
	Tab2Text="Minions">
	<local:SimSegmentedControl.Padding>
		<OnPlatform x:TypeArguments="Thickness">
			<On Platform="Android" Value="0" />
			<On Platform="iOS" Value="10,0,10,10" />
		</OnPlatform>
	</local:SimSegmentedControl.Padding>
</local:SimSegmentedControl>

 

Easy peasy, you just set the property values such as PriaryColor, SecondaryColor and so on that we created in our SimSegmentedControl and do a bit of customization if you wish to 😉 like I’ve added some padding for iOS!

In case if you’re wondering how to use the SelectedTabIndexChanged, you basically subscribe to that event and perform whatever the action you desire, whether it be changing some values, or swapping some Views or whatever your requirement is!

private void SegmentedControlView_SelectedTabIndexChanged
			(object sender, SelectedTabIndexEventArgs e)
{
	if (e.SelectedTabIndex == 1)
	{
		ContentView1.IsVisible = true;
		ContentView2.IsVisible = false;
	}
	else if (e.SelectedTabIndex == 2)
	{
		ContentView1.IsVisible = false;
		ContentView2.IsVisible = true;
	}
}

 

Just like that!

Let’s fire it up!

Let’s see this beauty in action now! 😀

Here we go baby! iOS and Android running side by side…

 

Let’s change up a bit of the colors shall we!

Woot, whatever the color combination you wish! 😉

Improvement suggestions..

Well if you ask me this is not the exact implementation I used for my actual requirement, this is more of a very simple implementation of it.

But there’s many ways to improve this. One would be adding Command for the selected Tab Index changed property handling. Also add both way handling of SelectedTabIndex so that we can set the default selected Tab on the go. Specially add dynamic Tab Buttons to the SimSegmentedControl at run time without just limiting to 2 buttons. 😉

Well your imagination is the limit fellas! 😀

This whole awesome project is hosted up in my Github repo : https://github.com/UdaraAlwis/XFSegmentedControl 

Check out the Part 2 of this article: Advanced Segmented Button Control in pure Xamarin.Forms!

Cheers! 😀 Keep on going my fellow devs!

Spread the love…

Build yo own awesome Activity/Loading Indicator Page for Xamarin Forms…

Have you ever wanted to have an Activity or Loading indicator dialog screen overlay, that is transparent, and fully customized by you? in your Xamarin.Forms project?

Then you stopped at the right place.

Today I’m gonna share how to build a fully customizable Activity Indicator /Loading Screen from Xamarin.Forms with a bit of native magic. To be honest, more of a continuation of my previous blog post! 😉 lol

Perks:

  • Fully customizable View on the go from Xamarin.Forms
  • Overlays on top of your ContentPage / Navigation Stack
  • Service based, full MVVM & testing friendly
  • Fully transparent and controllable dimmer
  • Cancellation & back button disabled

Here’s a sneak peek…

  

TADAAA! That’s what yol gonna build! 😀

The Concept…

So basically if you think about it, when you want to display an Loading/Activity indicator overlay screen, it is something that would indicate,

“Oh there’s some important processing going on that Page and we need you to wait until it finishes…” 😛

“In the meantime we’re going to block the interactivity of that Page with this overlay, but you can still see the progress of it with the transparency…”

So in the language of Xamarin.Forms, on top of your ContentPage, we need something that would block the interactivity of background content but allows us to see what’s going in the background, in other words, it should be a transparent or dimmed View. 😀

A ghost from the past…

So I’m going to revert your attention to the previous blog post I wrote, Build your own Transparent Page from scratch for Xamarin.Forms, which was all about creating a Transparent page for Xamarin.Forms using a bit of native code. And I’ll be using the same concept and the code here as well, but I’m not going to drill down to the technical details of that specific implementation here, so if you’re looking for it, go ahead and give it a read first and come back.

The Recipe time…

So if you’re coming back  from my previous blog post you could probably consider this post as a continuation of it. Today we’re going to create a Transparent Page in Xamarin.Forms using a bit of native magic, that will overlay on top of any Xamarin.Forms ContentPage or the Navigation Stack, and has the capability to customize the Transparent content view on demand. 😀

So to do this, we’re going to implement a native Transparent page in our Platform projects (iOS and Android), then we’re going to create a Service implementation that can display and dismiss our Transparent pages on demand while being able to pass in the desired Content View as we wish to display as parameters. The actual concrete implementation of that service will bed laid down in platform specific projects, along side the native Transparent page rendering implementation. So that we can do the rendering or displaying or dismissing our Loading/Activity indicator overlay on demand as we wish.

So to map the Service interface and its concrete implementations we are going to use Xamarin.Forms Dependency service, but then if you have your own IoC container you could use it as well. 😉

Sounds pretty straight forward eh! 😀 time for coding! 😉

Xamarin.Forms bits…

Alright then let’s hit it with the Service interface implementation. Let’s call it ILodingPageService.

public interface ILodingPageService
{
	void InitLoadingPage
                  (ContentPage loadingIndicatorPage = null);

	void ShowLoadingPage();

	void HideLoadingPage();
}

 

So we will have three interface methods, one to initiate and prepare the Transparent page we’re going to display as our Loading/Activity indicator overlay. Then two more to Show it or Hide it on the app.

Speaking of InitLoadingPage() method, the reason we need is to facilitate the feature of displaying different Loading pages or designs on demand at the run time. So let’s say in Page 1 we want to display one Loading page, then in Page 2 we want to display a different kind of Loading Page, that right there is possible here with this method. You just pass in whatever the Loading Page design you want to show, and you’re done! 😉 How cool is that!

Since this a Xamarin.Forms Transparent Page, let’s first create our usual ContentPage, with usual stuff. Let’s call it the LoadingIndicatorPage1

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="XFLoadingPageService.LoadingIndicatorPage1"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    BackgroundColor="#80000000">
    <ContentPage.Content>
        <StackLayout
            Padding="30"
            BackgroundColor="Black"
            HorizontalOptions="Center"
            VerticalOptions="Center">
            <ActivityIndicator IsRunning="True" Color="White" />
            <Label
                FontAttributes="Bold"
                Text="Loading..."
                TextColor="White" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

 

So you can see we have a very simple ContentPage design, with an ActivityIndicator and a Label to show that, “Oh look it’s a loading screen… boo!” lol 😀

Android bits….

Here come the actual magic, let me begin with Android! So let’s start off with our ILoadingPageService’s concrete implementation for Android and register it with the Xamarin Dependency Service.

[assembly: Xamarin.Forms.Dependency(typeof(LodingPageServiceDroid))]
namespace XFLoadingPageService.Droid
{
    public class LodingPageServiceDroid : ILodingPageService
    {
        private Android.Views.View _nativeView;

        private Dialog _dialog;

        private bool _isInitialized;

        public void InitLoadingPage(ContentPage loadingIndicatorPage)
        {
            // check if the page parameter is available
            if (loadingIndicatorPage != null)
            {
                // build the loading page with native base
                loadingIndicatorPage.Parent = Xamarin.Forms.Application.Current.MainPage;

                loadingIndicatorPage.Layout(new Rectangle(0, 0,
                    Xamarin.Forms.Application.Current.MainPage.Width,
                    Xamarin.Forms.Application.Current.MainPage.Height));

                var renderer = loadingIndicatorPage.GetOrCreateRenderer();

                _nativeView = renderer.View;

                _dialog = new Dialog(CrossCurrentActivity.Current.Activity);
                _dialog.RequestWindowFeature((int)WindowFeatures.NoTitle);
                _dialog.SetCancelable(false);
                _dialog.SetContentView(_nativeView);
                Window window = _dialog.Window;
                window.SetLayout(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
                window.ClearFlags(WindowManagerFlags.DimBehind);
                window.SetBackgroundDrawable(new ColorDrawable(Android.Graphics.Color.Transparent));

                _isInitialized = true;
            }
        }

        public void ShowLoadingPage()
        {
            // check if the user has set the page or not
            if (!_isInitialized)
                InitLoadingPage(new LoadingIndicatorPage1()); // set the default page

            // showing the native loading page
            _dialog.Show();
        }

        public void HideLoadingPage()
        {
            // Hide the page
            _dialog.Hide();
        }
    }
}

 

Most of the above Xamarin Android specific code is already explained in detailed line by line in my previous post. So in short, here we have the concrete implementation of our service for Android, inside the InitLoadingPage() we’re passing in the Xamarin.Forms Page which we want to render as a transparent page which will act as our Activity Indicator.  Then we’re rendering that page and embed into a Android Dialog view with a transparent background, and back button cancelled properties enabled. We’re keeping a reference of the _dialog instance so that we can show or hide the Page upon respective ShowLoadingPage() and HideLoadingPage() executions.

So every time a user wants to display a different Loading page, they will call the InitLoadingPage() which will build the new page instance and keep it in the service memory.

At the same time you may have seen inside ShowLoadingPage() if you haven’t instantiated the transparent page, then we’re using a default page, LoadingIndicatorPage1 as a template ad instantiating it on the go, just to avoid exceptions. This choice of default page is totally up to you.

Also don’t forget at the top of the namespace we’re registering this concrete implementation with Xamarin Dependency service. 😉

iOS bits….

Then let’s move on with our ILoadingPageService’s concrete implementation for iOS and register it with the Xamarin Dependency Service.

[assembly: Xamarin.Forms.Dependency(typeof(LodingPageServiceiOS))]
namespace XFLoadingPageService.iOS
{
    public class LodingPageServiceiOS : ILodingPageService
    {
        private UIView _nativeView;

        private bool _isInitialized;
        
        public void InitLoadingPage(ContentPage loadingIndicatorPage)
        {
            // check if the page parameter is available
            if (loadingIndicatorPage != null)
            {
                // build the loading page with native base
                loadingIndicatorPage.Parent = Xamarin.Forms.Application.Current.MainPage;

                loadingIndicatorPage.Layout(new Rectangle(0, 0,
                    Xamarin.Forms.Application.Current.MainPage.Width,
                    Xamarin.Forms.Application.Current.MainPage.Height));

                var renderer = loadingIndicatorPage.GetOrCreateRenderer();

                _nativeView = renderer.NativeView;

                _isInitialized = true;
            }
        }

        public void ShowLoadingPage()
        {
            // check if the user has set the page or not
            if (!_isInitialized)
                InitLoadingPage(new LoadingIndicatorPage1()); // set the default page

            // showing the native loading page
            UIApplication.SharedApplication.KeyWindow.AddSubview(_nativeView);
        }

        public void HideLoadingPage()
        {
            // Hide the page
            _nativeView.RemoveFromSuperview();
        }
    }
}

 

So the implementation here is also similar to Android code above, except for the native bit. So we’re instantiating the Xamarin.Forms Page instance inside, InitLoadingPage() method we’re initiating the transparent page instance and holding inside the service.

Then showing it or hiding it based on the ShowLoadingPage() or HideLoadingPage() calls.

Pretty straightforward eh! 😀

So what next…

Now one of the best features of this implementation is that your could use any number of Loading Indicator Pages as you wish with various kinds of designs. 😀 So just for the kicks of it here’s another page that we’ll use. let’s call it LoadingIndicatorPage2

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage
    x:Class="XFLoadingPageService.LoadingIndicatorPage2"
    xmlns="http://xamarin.com/schemas/2014/forms"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    BackgroundColor="#80000000">
    <ContentPage.Content>
        <StackLayout
            Padding="30"
            BackgroundColor="#D93463"
            HorizontalOptions="Center"
            VerticalOptions="Center">
            <ActivityIndicator IsRunning="True" Color="White" />
            <Label
                FontAttributes="Bold"
                Text="Yo! Hold on..."
                TextColor="White" />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

 

If that’s not enough you can add more and more as you go 😀 but just make sure to call the InitLoadingPage() method! 😉

Let’s fire it up…

So to fire this up we need to call this service from your Xamarin.Forms code using the DependencyService.

// show the loading page...
DependencyService.Get<ILodingPageService>()
                 .InitLoadingPage(new LoadingIndicatorPage1());
DependencyService.Get<ILodingPageService>().ShowLoadingPage();

 

There we’re first initiating our page and then show it on the app. Once you initiate the page you don’t have to call it ever again as you saw in the implementation, it is retained in the memory of the service.

// close the loading page...
DependencyService.Get<ILodingPageService>().HideLoadingPage();

 

Once you’re done, you can close our awesome Activity / Loading Indicator Page with the above code.

And here we go on iOS and Android in action…. 😀

That’s our first Loading screen in action…

And click on the second button, there’s our second Loading screen in action, on the go…

Look at that, even during navigation between pages our Loading page stays intact on top of the Xamarin.Forms Pages stack. 😉

The reason why it acts so independently is because we are directly accessing the native elements in the service implementation, therefore even during navigation of Xamarin.Forms Stack or whatever the UI activity our Loading page will not be affected, it will keep on, of its own.

How awesome is that eh! 😀

Github it if yo lazy!

So all of this is hosted on my git repo: https://github.com/XFLoadingPageService

Now your own imagination is the limit for what’s possible or not fellas!

That’s it for today.

Cheers! 😀

Build your own Transparent Page from scratch for Xamarin.Forms…

There was this one time I wanted to build my own Transparent Page in Xamarin Forms, from scratch, all by myself, due to my ego and to challenge myself.

Usually when it comes to Transparent page related situations I would always recommend the awesome Rg.Plugins.Popup  library, which I had praised one of my previous blog posts as well, So I created a Popup with Transparent background in Xamarin Forms… 😉

Backstory…

But for real there was one instance I couldn’t use any 3rd party library for the project and all the code bits should be from scratch. So I had no option but to resort myself to creating my own Transparent Page in that Xamarin.Forms project.

And I did…

Sneak Peak…

So this how it would look like.

And limit of the expansion is all up to your imagination and developer skills.

If not work on it! 😛

Recipe time!

So to create a transparent page in Xamarin.Forms out of the box is impossible, which I’m not going to explain in detail. Obviously in short, for reasons such as Xamarin.Forms abstracts the most common subset of properties of the native platforms, we don’t have much power of customization of the UI.

There is no way to use Xamarin.Forms ContentPage with transparency. (Yes I have tried!) So we need something beyond Xamarin.Forms stuff, Aha! Natively Rendered View, that could overlay on top of a give ContentPage.

But that doesn’t mean Xamarin.Forms would block you from implementing something platform specific, it only empowers you 😉

Also since we’re drilling down in the native levels, we have absolute control over Xamarin.Forms Pages, including the power to push any View on top of Xamarin.Forms ContentPage Navigation stack.

Recipe in-depth!

So to do this we need to have some Native platform level access, so if you’re using a Xamarin.Forms shared project, this should be pretty easy, but for PCL projects, you may have to create a dependency service implementation to invoke this implementation.

So in Android, we’re going to use Dialog View to implement the transparent Page and with the access of the Activity instance, we’ll push it to over any give ContentPage of Xamarin.Forms.

Then in iOS, we’ll be using UIApplication instance’s KeyWindow property to push the transparent Page over any given ContentPage of Xamarin.Forms.

Sounds pretty straight forward eh! 😀

Xamarin.Forms bits…

Alright since this a Xamarin.Forms Transparent Page, let’s first create our usual ContentPage, with usual stuff.

var xamFormsPage = new ContentPage() 
{
  BackgroundColor = new Color(0, 0, 0, 0.5),
  Content =
  new StackLayout() 
  {
    Padding = 30,
    Spacing = 20,
    WidthRequest = 250,
    BackgroundColor = Color.Black,
    Children = 
	{
	 new Xamarin.Forms.Label() {
	  Text =
	   "Welcome to my own Transparent Page!",
	   FontAttributes = FontAttributes.Bold,
	   TextColor = Color.White,
	   FontSize = 20,
	 },
	 new Xamarin.Forms.Label() {
	  Text =
	   "This is from Xamarin.Forms with a " +
	   "bit mix of simple native magic!",
	   TextColor = Color.White,
	   FontSize = 17,
	 },
	 new Xamarin.Forms.Button() {
	  Text = "Close me!",
	   BackgroundColor = Color.Gray,
	   TextColor = Color.White,
	 }
    },
    VerticalOptions = LayoutOptions.Center,
    HorizontalOptions = LayoutOptions.Center,
  }
};

 

So here we have an instance of a simple Xamarin.Forms.Content page, with a bunch of labels and a button. This is the page we’re going to render into a transparent page. 😉

Android Implementation…

So like we discussed before, on Android we’re going to make use of the Android Dialog View to populate our transparent page. In order to do this we need to get access to the current Activity of our Xamarin.Forms Android run time.

In order to do that we’re going to use CrossCurrentActivity plugin by James Montemagno. So before we begin, go ahead and add that plug in to your Xamarin.Forms solution using Nuget.

Now the basic idea here is all about actually rendering our Xamarin.Forms ContentPage instance, and converting it to a native Android View at run time. Then we take that native View instance and attach into a Android Dialog View, making it visible along with the transparent effect. Oh yes the CrossCurrentActivity plugin comes handy when we instantiate our Android Dialog View. 😉

// Assign the Parent hook for our page instance 
xamFormsPage.Parent = Xamarin.Forms.Application.Current.MainPage;

// Run the Layout Rendering Cycle for the page
xamFormsPage.Layout(new Rectangle(0, 0,
 Xamarin.Forms.Application.Current.MainPage.Width,
 Xamarin.Forms.Application.Current.MainPage.Height));

// Get the native renderered instance for our page
var nativePageRendererInstance = xamFormsPage.GetOrCreateRenderer();

// Get the native page for our page
Android.Views.View nativePageView = nativePageRendererInstance.View;

// Create the native transparent Dialog instance to embed our page
Dialog dialog = new Dialog(CrossCurrentActivity.Current.Activity);
dialog.RequestWindowFeature((int) WindowFeatures.NoTitle);
dialog.SetCancelable(false);
dialog.SetContentView(nativePageView);
Window window = dialog.Window;
window.SetLayout(ViewGroup.LayoutParams.MatchParent, ViewGroup.LayoutParams.MatchParent);
window.ClearFlags(WindowManagerFlags.DimBehind);
window.SetBackgroundDrawable(new ColorDrawable(Android.Graphics.Color.Transparent));

// Show the page
dialog.Show();

 

There you have the magical code 😉 lol.

You can see how we’re setting the Parent hook to our Xamarin.Forms page instance, then running the Layout() rendering circle allowing the Views to be actually measured and rendered in the memory. Then we convert our Xamarin.Forms page instance into a native Android View using the GetOrCreateRenderer() extension method which I will describe next.

Then as I discussed before we’re attaching the native View into a Dialog View and setting it visible resulting in total awesome transparency of a page, along with the exact Xamarin.Forms content we wanted to display.

Oh before I forget here is the precious Xamarin.Forms.View -> Android.Views.View Converter extension implementation. Special thanks to rotorgames for the below magical code block. 😉

internal static class PlatformExtension
{
	public static IVisualElementRenderer GetOrCreateRenderer(this VisualElement bindable)
	{
		var renderer = XFPlatform.GetRenderer(bindable);
		if (renderer == null)
		{
			renderer = XFPlatform.CreateRendererWithContext(bindable, CrossCurrentActivity.Current.Activity);
			XFPlatform.SetRenderer(bindable, renderer);
		}
		return renderer;
	}
}

Source Credit: Rg.Plugins.Popup.Droid/PlatformExtension.cs

As you can see it’s a simple implementation that takes in the Xamarin.Forms View instance and retrieve the native renderer for that View.

Now when you need to hide the above Transparent page, you simply call Hide() on the Android Dialog instance.

// Hide the page
dialog.Hide();

 

Then we go to the iOS stuff..

iOS Implementation….

Here we’ve come to the iOS implementation, so just like we discussed in the beginning, we’re going to access the global UIApplication singleton to push our transparent page the application view through the KeyWindow property.

So in a nutshell iOS renders every native View with the transparency give the proper background spacing, so we don’t really have to worry about using any placeholder view. The idea here is to get our Xamarin.Forms Page instance, run its Layout rendering cycle, convert that instance to an iOS native View. Then finally push it to the KeyWindow property by adding as a SubView.

Pretty straightforward, almost similar as to what we did in Android but simpler! 😉

// Assign the Parent hook for our page instance 
xamFormsPage.Parent = Xamarin.Forms.Application.Current.MainPage;

// Run the Layout Rendering Cycle for the page
xamFormsPage.Layout(new Rectangle(0, 0,
 Xamarin.Forms.Application.Current.MainPage.Width,
 Xamarin.Forms.Application.Current.MainPage.Height));

// Get the native renderered instance for our page
var nativePageRendererInstance = xamFormsPage.GetOrCreateRenderer();

// Get the native page for our page
UIView nativePageView = nativePageRendererInstance.NativeView;

// Show the page by pushing to the stack
UIApplication.SharedApplication.KeyWindow.AddSubview(nativePageView);

 

I’m not going repeat myself here because I’m too lazy and the explanation is almost same as I did in Android implementation. 😀

But in the context of iOS, you can see we’re getting the iOS native UIView of our Xamarin.Forms ContentPage instance and pushing it directly to the Application UI, by calling AddSubView() on KeyWindow property.

Oh before I forget here is the precious Xamarin.Forms.View -> UIKit.UIView Converter extension implementation. Special thanks to rotorgames for the below magical code block. 😉

internal static class PlatformExtension
{
	public static IVisualElementRenderer GetOrCreateRenderer(this VisualElement bindable)
	{
		var renderer = XFPlatform.GetRenderer(bindable);
		if (renderer == null)
		{
			renderer = XFPlatform.CreateRenderer(bindable);
			XFPlatform.SetRenderer(bindable, renderer);
		}
		return renderer;
	}
}

Source Credit: Rg.Plugins.Popup.IOS/PlatformExtension.cs

Now when you want to hide the above created Transparent Page, then you simple call the RemoveFromSuperview() on our iOS UIView instance, which will result in it removing itself from UIWindow.

// Hide the page
nativePageView.RemoveFromSuperview();

 

bloopity blah! 😀

Alright, so let me address something you might be wondering…

How about Xamarin.Forms to Xamarin Native bridge?

Now you might ask how am I going to bridge the above explained Xamarin.Forms and Xamarin Native implementation counterparts together? Now that’s some easy peasy nibbles I’m gonna leave up to your creativity or requirement.

There’s many ways to call back and forth between Xamarin.Forms or Xamarin Native project levels, or in other words, between the PCL project and the Platform Specific projects. For starters, you could use Xamarin Dependency Service to register a service interface and concrete implementation to communicate between these two layers back and forth. 😉 And many other possibilities, so your creativity is the limit.

However I will probably be writing another blog post regarding this with a full implementation of this with some cool application of it! 😉

Well frankly, that’s it fellas.

Cheers! 😀

Ze Flippable View in Xamarin.Forms with Native Animations…

Let’s blend some Native Animation goodness to our Flippin’ Flipity Flippable View in Xamarin.Forms…

So I hop yol’ remember my previous post, It’s a Flippin’ Flipity Flippable View in Xamarin.Forms! where I showcased my awesome control built right from Xamarin.Forms without any native code implementation. 😉

  

But you may have noticed a slight issue in the Flip Animation, specially on Android and iOS as well (slightly though), where Flip animation moves the View out of it’s bounds.

^As you can see above, in the animation screenshots… 😮

Some improvement needed…

If you look closely, during the flip rotation, the View sort of scales up itself and moves out of the bounds of itself and scales back and revert back to the normal bounds.

This was kind of annoying me from a personal perspective, so that’s why I thought of finding a solution by trying to render the whole animation natively for Android and iOS separately. 😀

Behold ze Native Animation…

So basically the whole logic of the FlipViewControl is going to be the same, only the animation part would be executed natively. Let’s discuss how we could implement a native animation for each Android and iOS below. 😀

As of Android…

As of Android, the reason why the View scales out of bounds during the flip animation is because that is the default behavior of Flip Animation in Android. Since Xamarin.Forms Aniamtions binds to the native default behavior you could definitely expect it to behave that way. There’s an aspect called Camera View distance perspective for any given view, by default during any animation the Camera View aspect doesn’t change, thus causing the overblown effect of the Flip Animation.

So by implementing a native animation what we could achieve is to control the Camera View Distance value for each animation frame manually, also something to keep in mind this needs to be done according to the Screen density. I found this solution thanks to this forum post:  https://forums.xamarin.com/discussion/49978/changing-default-perspective-after-rotation

As of iOS…

Here for the iOS its not much of an issue, but you do see a bit of the View scaling out of the boundary. So let’s dive into the iOS native flip animation.

We’ll be using a CATransform3D to maintain the transformation of the View’s Layer and execute the animation using UIView.Animate(), we will be using two CATransform3D objects to make sure the View doesn’t scale beyond the boundaries during the animation. This whole awesome solution I found via a random snippet search https://gist.github.com/aloisdeniel/3c8b82ca4babb1d79b29

Time for some coding…

Let’s get started off with the subclassed custom control, naming it XNFlipView and the implementation is actually same as our previous XFFlipView control implementation, but the only difference is there’s no Xamarin.Forms Animation implementation, or handling of the IsFlipped property in the PCL code, since it will be handled in the Renderer level.

public class XNFlipView : ContentView
{
	public XNFlipView()
	{
		...
	}

	public static readonly BindableProperty FrontViewProperty
	...

	public static readonly BindableProperty BackViewProperty
	...
	
	// Everything else is same as XFFlipView implementation

	public static readonly BindableProperty IsFlippedProperty =
	BindableProperty.Create(
		nameof(IsFlipped),
		typeof(bool),
		typeof(XNFlipView),
		false,
		BindingMode.Default,
		null);

	/// <summary>
	/// Gets or Sets whether the view is already flipped
	/// ex : 
	/// </summary>
	public bool IsFlipped
	{
		get { return(bool)this.GetValue(IsFlippedProperty);}
		set { this.SetValue(IsFlippedProperty, value); }
	}
	
	...
}

 

You can take a look at the full class implementation in the github repo file: XFFlipViewControl/XNFlipView.cs

Native Renderers implementation…

Since the animations are going to be handled natively, we need to create the Custom Renderers for our XNFlipView for Android and iOS separately, so let’s get started…

Android Custom Renderer

Alright then let’s go ahead and create the XNFlipViewRenderer  extending from ViewRenderer, as of Xamarin.Forms 2.5 and later we have to pass the Context in the Custom Renderer’s constructor, so let’s begin with that.

public class XNFlipViewRenderer : ViewRenderer
{
	private float _cameraDistance;

	private readonly ObjectAnimator _animateYAxis0To90;
	private readonly ObjectAnimator _animateYAxis90To180;

	public XNFlipViewRenderer(Context context) : base(context)
	{
		...
		//Animation Initialization
		...
	}

	protected override void 
		OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.View> e)
	{
		base.OnElementChanged(e);

		if (((XNFlipView)e.NewElement) != null)
		{
			// Calculating Camera Distance 
                        //to be used at Animation Runtime
			// https://forums.xamarin.com/discussion/49978/changing-default-perspective-after-rotation
			var distance = 8000;
			_cameraDistance = Context.Resources.DisplayMetrics.Density * distance;
		}
	}

	protected override void 
		OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
	{
		base.OnElementPropertyChanged(sender, e);

		if (e.PropertyName == XNFlipView.IsFlippedProperty.PropertyName)
		{
			if (!((XNFlipView)sender).IsFlipped)
			{
				this.RotationY = 0;
			}

			AnimateFlipHorizontally();
		}
	}

	private void AnimateFlipHorizontally()
	{
		SetCameraDistance(_cameraDistance);

		_animateYAxis0To90.Start();
	}
}

 

Now as you can see above in the constructor we’re initializing the ObjectAnimator objects _animateYAxis0To90 and _animateYAxis90To180 which will be executing the native Flip Animation.

Then in the Renderer’s OnElementChanged we’re calculating the Camera distance value to be used during the Animations execution as we explained before in the concept.

Also you can see how we’re listening to the XNFlipView.IsFlipped value change and executing Animations.

Next let’s take a look into the Animation execution implementation which goes inside the Constructor as you can see in the previous code snippet…

// Initiating the first half of the animation
_animateYAxis0To90 = ObjectAnimator.OfFloat(this, "RotationY", 0.0f, -90f);
_animateYAxis0To90.SetDuration(500);
_animateYAxis0To90.Update += (sender, args) =>
{
	// On every animation Frame we have to update the Camera Distance since Xamarin overrides it somewhere
	SetCameraDistance(_cameraDistance);
};
_animateYAxis0To90.AnimationEnd += (sender, args) =>
{
	if (((XNFlipView)Element).IsFlipped)
	{
		// Change the visible content
		((XNFlipView)Element).FrontView.IsVisible = false;
		((XNFlipView)Element).BackView.IsVisible = true;
	}
	else
	{
		// Change the visible content
		((XNFlipView)Element).BackView.IsVisible = false;
		((XNFlipView)Element).FrontView.IsVisible = true;
	}

	this.RotationY = -270;

	_animateYAxis90To180.Start();
};

// Initiating the second half of the animation
_animateYAxis90To180 = ObjectAnimator.OfFloat(this, "RotationY", -270f, -360f);
_animateYAxis90To180.SetDuration(500);
_animateYAxis90To180.Update += (sender1, args1) =>
{
	// On every animation Frame we have to update the Camera Distance since Xamarin overrides it somewhere
	SetCameraDistance(_cameraDistance);
};

 

As you can see we’re instantiating the animation objects accordingly to the degree angle of the Y Axis they’re suppose to animate the view. Also something very important is that in each animation frame we’re also updating the Camera View Distance, as we discussed earlier this to prevent the View from scaling beyond it’s boundaries. That SetCameraDistance() call takes of it with the previous calculated value. 😉

You can also change the speed of the animation by changing the SetDuration() parameters, which currently I’ve set to 1 second.

You could take a look at the full implementation of the android custom renderer in the github file: XFFlipViewControl.Android/XNFlipViewRenderer.cs

iOS Custom Renderer

Alright then let’s move to the iOS Custom Renderer…

public class XNFlipViewRenderer : ViewRenderer

   protected override void
       OnElementPropertyChanged(object sender, PropertyChangedEventArgs e)
   {
       base.OnElementPropertyChanged(sender, e);

       if (e.PropertyName == XNFlipView.IsFlippedProperty.PropertyName)
       {
           if (((XNFlipView)sender).IsFlipped)
           {
             AnimateFlipHorizontally(NativeView, false, 0.5, () =>
             {
                 // Change the visible content
                 ((XNFlipView)sender).FrontView.IsVisible = false;
                 ((XNFlipView)sender).BackView.IsVisible = true;

                 AnimateFlipHorizontally
                           (NativeView, true, 0.5, null);
             });
           }
           else
           {
             AnimateFlipHorizontally(NativeView, false, 0.5, () =>
             {
                 // Change the visible content
                 ((XNFlipView)sender).FrontView.IsVisible = true;
                 ((XNFlipView)sender).BackView.IsVisible = false;

                 AnimateFlipHorizontally
                             (NativeView, true, 0.5, null);
             });
           }
       }
   }
   
   public void AnimateFlipHorizontally(...)
   {
       ...
   }

 

So here in iOS Renderer, it seems a bit straight forward as we’re simply listening to the IsFlipped property change and directly executing the animation.

Next let’s see the Animation implementation…

//https://gist.github.com/aloisdeniel/3c8b82ca4babb1d79b29
public void AnimateFlipHorizontally
	(UIView view, bool isIn, 
		double duration = 0.3, Action onFinished = null)
{
	var m34 = (nfloat)(-1 * 0.001);

	var minTransform = CATransform3D.Identity;
	minTransform.m34 = m34;
	minTransform = minTransform.
		Rotate((nfloat)((isIn ? 1 : -1) * Math.PI * 0.5),
			(nfloat)0.0f, (nfloat)1.0f, (nfloat)0.0f);
	var maxTransform = CATransform3D.Identity;
	maxTransform.m34 = m34;

	view.Layer.Transform = isIn ? minTransform : maxTransform;
	UIView.Animate(duration, 0, UIViewAnimationOptions.CurveEaseInOut,
		() => {
			view.Layer.AnchorPoint = new CGPoint((nfloat)0.5, (nfloat)0.5f);
			view.Layer.Transform = isIn ? maxTransform : minTransform;
		},
		onFinished
	);
}

 

So that’s basically the animation implementation code, which I have extracted from the given gist link at the top, which I have explained in the concept description as well.

You can change the speed of the flip animation by changing the duration.

You could take a look at the full implementation of the android custom renderer in the github file: XFFlipViewControl.iOS/XNFlipViewRenderer.cs

Try it out eh! 😀

Well its use is exactly same as our previous XFFlipView Control. As of an example you could take a look here in my github file: XNFlipViewDemoPage.xaml

So now to execute the awesome Flip Animation, simply change the value of the IsFlipped as follows.

XNFlipViewControl1.IsFlipped = !XNFlipViewControl1.IsFlipped;

 

As you can see in code behind, we’re changing the value of the control’s IsFlipped property, Simples eh! 😀 This is fully bindable as well, so you can directly bind this to a ViewModel property as well.

...
<xfFlipViewControl:XNFlipView 
     x:Name="XNFlipViewControl1" 
          IsFlipped="{Binding IsViewFlipped}">
...

</xfFlipViewControl:XNFlipView>

 

So you can directly use this in your beautifully crafted MVVM Xamarin.Forms app as well. 😀

Some Live Action…

Here we go baby! iOS and Android running side by side…

 

 

Woot!

Look at that the Flip Animation maintains the Bounds of the View nicely during the animation in both Android and iOS! 😉

This whole awesome project i hosted up in my Github repo : https://github.com/UdaraAlwis/XFFlipViewControl 

Cheers! 😀 Keep on going my fellow devs!

Spread the love…

Xamarin Forms cross platform architectural implementation patterns…

Let’s talk about how to properly handle advanced cross platform architectural implementations in Xamarin Forms projects, specifically when you’re abstracting native services/implementations in your shared code base, while trying to maintain loosely-coupled and scalable architecture.

Yaay! Xamarin Forms!

Now we all know how Xamarin Forms allows us to build cross platform mobile apps while sharing almost up to 100% of our code base and skill having native performance and look and feels.
It does this by adding a common layer of abstraction which shares properties and behaviors which are common for the native platforms.

BUT…

Despite the incredible architecture of the Framework, one of the main drawbacks of it is that we do not get access to 100% of the native properties and behaviors, thus we only get the “common subset” of behaviors of each native platform that are shareable in a common manner among all the platforms through Xamarin Forms.

OPS…

So when we need to access some properties, behaviors or services that’s not available from Xamarin Forms layer, we need to drill down to the native platform specific level of that certain platform.
Now for UI Controls and their properties or behaviors we could use Custom Renderes or Effects.

But how about inbuilt native Services, such as Storage, Text-to-Speech, Location and so on?

ABSTRACTION FTW!

Turns out it’s all abstraction of an interface and mapping it to a platform specific concrete implementation, which could be described as the famous “Bridge Pattern”.

A BUMMER..

Yes it does seem pretty simple but when it comes to actual practicality of it, then it becomes a little bit complicated or rather messy, unless you follow a proper implementation pattern.
And it only gets more complicated when you keep on scaling your app project.
Therefore it’s very crucial that we maintain a certain set of principal patterns when we do platform specific implementation with abstraction mapping.

THE SOLUTION?

So we need to make sure that we maintain a proper set of principal patterns when deal with this situation as I explained earlier.
Here I’m going to talk about three key principles to deal with advanced cross platform implementations for handling native abstractions.

  • Factory Pattern
  • Service Locator Pattern
  • Dependency Injection Pattern

Now with the above principle patterns you could maintain a properly constructed and easily scalable Xamarin Forms project solution, when you’re dealing with advanced cross platform implementations with abstracting native services. Or rather any kind of an abstraction service implementation you could keep properly maintained by following the above patterns. The key advantage in all the above patterns are decoupled code, and scalability at any given time.

Now keep in mind there’s actually many kinds of patterns you could follow in this scenario or you could come up with your own architectural patterns, but the above are known to be most used among Xamarin Forms projects.

It is best to be aware of them, since you could either use them straight away or modify them according to your requirements. And keep in mind the above principle patterns could become slightly changed from their literal definition when it comes to actual implementation, it’s only the foundation concept that we need to keep in mind when we implement them, and make sure we are following the basics of it at least.

Which one should I use?

There is no such thing as “the best” or “the worse”pattern for cross platform mobile development, it all depends on how you interpret it based on your requirements. The selection of which pattern or architecture suits best for you is totally up to you and your requirements, that is something very crucial to keep in mind. Therefore here in this post I shall be demonstrating each of the above patterns and how to implement them properly in a Xamarin Forms project solution for the same app concept.

Let’s talk Demonstration!

In order to properly demonstrate the above said patterns I will be implementing a simple Xamarin Forms app which allows you to writing notes, save them, view them, read them out loud, edit them, and also delete them. So in that case we will be using native Storage Services and Text-To-Speech Services of those native platforms, while having a shared code base.

Alright now, I’m not going to get into spoon feeding details of how to do each native services implementation such as Storage and Text-To-Speech and implementing the XAML pages for the app and so on, but I will only be focusing on implementing the pattern for the given scenario, which is what matters for this post.

So we are going to create a Xamarin Forms solution in Visual Studio, and keep the interface for the above native services in the PCL or Shared Project (INoteReader and INoteLoader) and have the concrete implementations of them to be moved down to the native projects.

Then to demonstrate the differences of implementation of all the above three patterns I have created a complete solution (XFCPMobilePatterns) which has three sub folders, and included three Xamarin Forms projects in each of them which has the demo for Factory Pattern (XFMyNotesAppFP), Service Locator Pattern (XFMyNotesAppSL) and Dependency Injection w/ IoC (XFMyNotesAppDI).

Yep, that’s how it would look, if you’re interested in diving further into the implementation, You may find the complete solution up on my Github repo: https://github.com/UdaraAlwis/XFCPMobilePatterns

Let’s begin.

1. FACTORY PATTERN with Xamarin Forms

Oh yeah, back to basics yeah? the good old Factory Pattern, which allows you to create objects without exposing the creation logic to the client, or as in without having to aware of the concrete implementation.

So for our implementation we are going to keep a static generic Factory which will handle mapping and creation of the services. And we would request the service by passing the service type.

public static class ServiceLoaderFactory<T>
{
    public static Func<T> CreateService { get; set; }
}

 

Alright next we are going to map our Service Interfaces (INoteReader and INoteLoader) which we have placed in the PCL project, with their actual concrete implementations in the platform specific projects using the ServiceLoaderFactory. Make sure to do this mapping in the run time execution point of each project as shown below.

// Android implementation
protected override void OnCreate(Bundle bundle)
{
	TabLayoutResource = Resource.Layout.Tabbar;
	ToolbarResource = Resource.Layout.Toolbar;

	base.OnCreate(bundle);

	global::Xamarin.Forms.Forms.Init(this, bundle);

	ServiceLoaderFactory<INoteLoader>.CreateService = () => new NoteLoaderDroid();
	ServiceLoaderFactory<INoteReader>.CreateService = () => new NoteReaderDroid();

	LoadApplication(new App());
}

// iOS implementation
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
	global::Xamarin.Forms.Forms.Init();
	LoadApplication(new App());

	ServiceLoaderFactory<INoteLoader>.CreateService = () => new NoteLoaderIos();
	ServiceLoaderFactory<INoteReader>.CreateService = () => new NoteReaderIos();

	return base.FinishedLaunching(app, options);
}

// UWP implementation
public App()
{
	ServiceLoaderFactory<INoteLoader>.CreateService = () => new NoteLoaderUwp();
	ServiceLoaderFactory<INoteReader>.CreateService = () => new NoteReaderUwp();

	this.InitializeComponent();
	this.Suspending += OnSuspending;
}

 

Next we need a NoteManager which is going to keep tract of all the service instances after they’re mapped to their concrete implementations at the run time, and also to maintain sort of a ‘facade-like’ access to the services. So for obvious reasons, we need to make it a singleton access point, as there’s no point of duplicating service objects. Also we are creating the NoteManager to handle basic functions such as loading and saving Notes at run time. 🙂

  public class NoteManager
  {
        // make a singleton access point
        private static readonly NoteManager _instance 
                                          = new NoteManager();
        public static NoteManager Instance 
                                  { get { return _instance; } }


        public IList<MyNote> MyNotes { get; private set; }


        public INoteLoader NoteLoader { get; private set; }
        
        public INoteReader NoteReader { get; private set; }

        private NoteManager()
        {
            NoteLoader = ServiceLoaderFactory<INoteLoader>.CreateService();
            NoteReader = ServiceLoaderFactory<INoteReader>.CreateService();

            MyNotes = new ObservableCollection<MyNote>(NoteLoader.Load());
        }

        public void Save()
        {
            NoteLoader.Save(MyNotes);
        }
  }

 

You can see there in the constructor, how we are loading the Service objects from our ServiceLoaderFactory and mapping them to the public interface instances, so that we could use them anywhere in our app.

Now the reason why I’m maintaining the NoteLoader and NoteReader instances here is because with the Factory Pattern, every time we request a service instance, it creates a new instance of the service and returns to the client, which obviously is not efficient, that’s why I’m retaining those instances in the NoteManager class. But with few tweaks you could easily implement a Factory Pattern which caches instances, and reuse them upon request, but I wouldn’t waste time on that, since we could use Service Locator or Dependency Injection for such scenarios, which I would explain later in the article.

Here’s how to access the above services in anywhere your PCL or Shared Project.

NoteManager.Instance.NoteReader.Speak("Hello, read this!");

 

There you have it, now that shows how to add platform dependent services and use them in your shared code following the Factory Pattern, as you go on scaling up the project solution! 😉

But keep in mind that this may not exactly according to literal definition of “Factory Pattern 101” but rather a customized version of it which I came up with for cross platform implementation, so you might have a different kind of implementation of the same concept, which is totally ‘ok’, as long as the foundation is the same. 🙂

2. SERVICE LOCATOR PATTERN with Xamarin Forms

As we already know, Service Locator Pattern, is all about locating a concrete implementation instance of an abstracted service interfaces at run time.
This is something similar to Factory Pattern, but a different type of a solution for our situation, whereas it maintains a dictionary of registered services which has been mapped with their concrete implementation, which we can look up at run time and retrieve the instance. Now it is considered that Service Locator pattern is a variation of Inversion of Control principle, just as Dependency Injection pattern, which we’ll discuss in the next topic.

This provides an on demand service look up at anywhere in the run time. The native service instances are stored in a dictionary-like data structure inside the Service Locator object, and returned at run time when they’re requested by the interface type. Obviously there will be a singleton static reference to the Service Locator object.

There’s many Service Locator ready-made libraries out there, and heck even Xamarin Forms already provides a solid Service Locator in the framework, which you may have already heard of, Xamarin Dependency Service. So you could use it right out of the box in Xamarin Forms, for your abstracted service implementations.

But that being said it’s not so hard to roll out our own Service Locator (just for the demonstration of it’s mechanics). 😉

So let’s implement our own simple Service Locator, this was actually something I grabbed off of github.

/// <summary>
///     Simple ServiceLocator implementation.
///     Extracted source credit : https://github.com/Azure-Samples/MyDriving/blob/master/src/MobileApps/MyDriving/MyDriving.Utils/ServiceLocator.cs
/// </summary>
public sealed class ServiceLocator
{
	static readonly Lazy<ServiceLocator> instance = new Lazy<ServiceLocator>(() => new ServiceLocator());
	readonly Dictionary<Type, Lazy<object>> registeredServices = new Dictionary<Type, Lazy<object>>();

	/// <summary>
	///     Singleton instance for default service locator
	/// </summary>
	public static ServiceLocator Instance => instance.Value;

	/// <summary>
	///     Add a new contract + service implementation
	/// </summary>
	/// <typeparam name="TContract">Contract type</typeparam>
	/// <typeparam name="TService">Service type</typeparam>
	public void Add<TContract, TService>() where TService : new()
	{
		registeredServices[typeof(TContract)] =
			new Lazy<object>(() => Activator.CreateInstance(typeof(TService)));
	}

	/// <summary>
	///     This resolves a service type and returns the implementation. Note that this
	///     assumes the key used to register the object is of the appropriate type or
	///     this method will throw an InvalidCastException!
	/// </summary>
	/// <typeparam name="T">Type to resolve</typeparam>
	/// <returns>Implementation</returns>
	public T Resolve<T>() where T : class
	{
		Lazy<object> service;
		if (registeredServices.TryGetValue(typeof(T), out service))
		{
			return (T)service.Value;
		}

		return null;
	}
}

 

As you can see how simple and straightforward it is. We maintain a singleton instance of the ServiceLocator, and there are the Add<TContract, TService>() which is used for registering the service interfaces with their concrete implementation and the Resolve<T>() which is used for retrieving the service instance at run time.

Notice how its maintaining a Dictionary of the service instances and retrieve it up on Resolve() call. 😉

Let’s add the above Service Locator to our project and construct it as below. And keep in mind the service implementation is going to be the same, having your service interfaces in the PCL shared project and the concrete implementations in the platform specific projects.

Now with our Service Locator this is how you would register your Service Interfaces (INoteReader and INoteLoader) with their concrete implementations.

// Android implementation
protected override void OnCreate(Bundle bundle)
{
	TabLayoutResource = Resource.Layout.Tabbar;
	ToolbarResource = Resource.Layout.Toolbar;

	base.OnCreate(bundle);

	global::Xamarin.Forms.Forms.Init(this, bundle);
	
	ServiceLocator.Instance.Add<INoteLoader, NoteLoaderDroid>();
	ServiceLocator.Instance.Add<INoteReader, NoteReaderDroid>();
	
	LoadApplication(new App());
}

// iOS implementation
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
	global::Xamarin.Forms.Forms.Init();

	ServiceLocator.Instance.Add<INoteLoader, NoteLoaderIos>();
	ServiceLocator.Instance.Add<INoteReader, NoteReaderIos>();

	LoadApplication(new App());

	return base.FinishedLaunching(app, options);
}

// UWP implementation
public App()
{
	ServiceLocator.Instance.Add<INoteLoader, NoteLoaderUwp>();
	ServiceLocator.Instance.Add<INoteReader, NoteReaderUwp>();

	this.InitializeComponent();
	this.Suspending += OnSuspending;
}

 

Then just like what we had in Factory Pattern implementation we need a NoteManager which is going to handle basic Note managing functions such as loading and saving notes. 🙂

public class NoteManager
{
	// make a singleton access point
	private static readonly NoteManager _instance 
                                          = new NoteManager();
	public static NoteManager Instance 
                                  { get { return _instance; } }


	public IList<MyNote> MyNotes { get; private set; }
	
	private NoteManager()
	{
		var noteLoader = ServiceLocator.Instance.Resolve<INoteLoader>();
		MyNotes = new ObservableCollection<MyNote>(noteLoader.Load());
	}

	public void Save()
	{
		var noteLoader = ServiceLocator.Instance.Resolve<INoteLoader>();
		noteLoader.Save(MyNotes);
	}
}

 

As you can see, compared to the NoteManager we had in the Factory Pattern, this NoteManager is much more simplified and cleaner thanks to the ServiceLocator.

This is because ServiceLocator allows us to maintain a single instance of our services such as INoteLoader and INoteReader, thereby we do not have to worry about duplicating their instances, we could simply access them anywhere in our code.

You can see how its easily calling the ServiceLocator.Resolve<T> to retrieve the service instances. 🙂

Here’s how to access the above services in anywhere your PCL or Shared Project, and notice how we are directly accessing the service instance unlike in Factory Pattern thanks to the ServiceLocator.

ServiceLocator.Instance.Resolve<INoteReader>().Speak("Hello, read this!");

 

There you have it, now this clearly shows how easy it is to add more and more platform dependent services and use them in your shared code as you go on scaling up the project solution, all thanks to Service Locator Pattern! 😉 Altogether while simplifying the shared code compared to the Factory Pattern.

And keep in mind this is a well improved pattern over Factory Pattern, but it still depends on your requirement as to which one is best suited for your implement. 🙂

3. DEPENDENCY INJECTION with Xamarin Forms

Now this right here is like the holy grail or the most praised and most used pattern in our scenario. Dependency Injection is all about injecting dependencies to create a given object just as said by its name. This is all about automatically resolving the required dependencies at run time without having the client specifically looking it up and creating them and injecting them to the new object to be created. So we are delegating the whole dependency resolving to an automated mechanism, thus a very popular form of Inversion of Control principle, whereas a massive improvement over the Service Locator.

Service Locator is good enough, only for smaller scale projects, where as you register services manually and look them up on demand at run time. But when the project gets more bigger and complex, with a lot of inter-connecting service and dependencies, it is very hard to keep a track on all of them, and most likely you’ll up missing a whole bunch of required dependencies in your code. This is usually a common case when you move into patterns such as MVVM implement for your mobile project, where you deliberately loosely couple all the layers of your app project, and you could easily end up missing dependencies.

This is where Dependency Injection comes for the rescue, where as we inject the required dependencies in the constructor or as properties and delegate that whole process to an automated mechanism, which we call the “Container“. So whenever we implement a DI it always comes with a static singleton Container which manages all the dependencies and resolve them automatically at run time, and we just have to register the dependency mapping only with the container.

Now there’s so many kinds of Dependency Injection Containers out there for you to choose from, given the popularity of this pattern. Unity, Ninject, AutoFac, TinyIoC and so on are some examples. It’s also pretty straight forward to roll out our own, but for this demo I would use an existing DI Container, Unity, quite a popular counterpart in this space.

Alright then, first of all let’s add the Unity library to our solution.

Make sure to select your PCL project and all the platform specific projects when you’re adding Unity from nuget.

Let’s make use of the Dependency Injection with our IoC Container as below. Now there’s nothing to be changed in how you implement your abstract interfaces in your PCL shared project and concrete implementations in the platform specific projects. 🙂

Let’s create a static reference for our container instance.

public partial class App : Application
{
	// static DI Container instance
	public static UnityContainer Container { get; set; }

	public App()
	{
		InitializeComponent();
		MainPage = new NavigationPage(
                                new XFMyNotesAppDI.NoteListPage());
	}
	
	...
}

 

Next here’s our NoteManager which is going to handle basic Note managing functions such as loading and saving notes. 🙂 You might see something different than what we had in Service Locator.

public class NoteManager
{
	private readonly INoteReader _noteReader;
	private readonly INoteLoader _noteLoader;

	public IList<MyNote> MyNotes { get; private set; }
	
	public NoteManager(INoteLoader noteLoader, 
                                    INoteReader noteReader)
	{
		_noteReader = noteReader;
		_noteLoader = noteLoader;
		
		MyNotes = new 
                  ObservableCollection<MyNote>(_noteLoader.Load());
	}

	public void Save()
	{
		_noteLoader.Save(MyNotes);
	}
}

 

As you can see we are passing in the INoteLoader and INoteReader services to the constructor of the NoteManager, this means that NoteManger cannot exist without those parameters services. So what happens here is that, when we request an instance of the NoteManager, the IoC Container (Unity Container) will resolve those depending services instances and inject them into the NoteManager, whilst creating the NoteManager.

Look how simple and clear the NoteManager is compared to our Service Locator and Factory Pattern principles.

Also you can see that we are no longer maintaining a singleton static reference to the NoteManager like how we did in Service Locator, because we could do the same thing directly using our IoC Container as shown below. 🙂

public App()
{
	InitializeComponent();

	// resolve the NoteManager instance
	App.Container.RegisterType<NoteManager>(
                        new ContainerControlledLifetimeManager());
					 
	MainPage = 
             new NavigationPage(newXFMyNotesAppDI.NoteListPage());
}

 

That’s how we are registering our NoteManager instance with the container, and we are instructing the container to retain a single instance of it by passing in the ContainerControlledLifetimeManager() type object to it. Also its good to keep in mind there are several object life time management types in Unity Container which you could play around with.

One of the coolest things about IoC containers is that we could instruct it to how we need a certain object or a type should be managed in the run time of the app. 😉 Oh yeah, cool indeed!

Now with our Unity Container this is how you would register your Service Interfaces (INoteReader and INoteLoader) with their concrete implementations on the platform specific level.

Also something to keep in mind is that we need to instantiate our UnityContainer instance here in the platform specific level where the execution begins. 🙂

// Android implementation
protected override void OnCreate(Bundle bundle)
{
	TabLayoutResource = Resource.Layout.Tabbar;
	ToolbarResource = Resource.Layout.Toolbar;

	base.OnCreate(bundle);

	global::Xamarin.Forms.Forms.Init(this, bundle);
	
	App.Container = new UnityContainer();
	App.Container.RegisterType<INoteLoader, NoteLoaderDroid>();
	App.Container.RegisterType<INoteReader, NoteReaderDroid>();

	LoadApplication(new App());
}

// iOS implementation
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
	global::Xamarin.Forms.Forms.Init();

	App.Container = new UnityContainer();
	App.Container.RegisterType<INoteLoader, NoteLoaderIos>();
	App.Container.RegisterType<INoteReader, NoteReaderIos>();

	LoadApplication(new App());

	return base.FinishedLaunching(app, options);
}

// UWP implementation
public App()
{
	XFMyNotesAppDI.App.Container = new UnityContainer();
	XFMyNotesAppDI.App.Container.RegisterType<INoteLoader, NoteLoaderUwp>();
	XFMyNotesAppDI.App.Container.RegisterType<INoteReader, NoteReaderUwp>();

	this.InitializeComponent();
	this.Suspending += OnSuspending;
}

 

Thanks to the IoC Container you could easily access the NoteManager anywhere in your code, which will give you access to the static retained instance.

NoteManager _noteManager = App.Container.Resolve<NoteManager>();

 

And of course the services as well.

App.Container.Resolve<INoteReader>().Speak("Hello, read this!");

 

There you have it, now this clearly shows how easy it is to add more and more platform dependent services and use them in your shared code as you go on scaling up the project solution, all thanks to Dependency Injection Pattern! 😉

Specially you noticed how it simplifies our shared code compared to the Service Locator pattern. Also its worth it to notice, how using an IoC Container brings many useful features to the table that you could use to improve your code.

So again, which one should I use?

Now that should have given you a very good comparison between the use of,

  • Factory Pattern
  • Service Locator Pattern
  • Dependency Injection Pattern

Each one of those patterns have their own advantages and disadvantages, yet you may have noted a general aspect improvement over each other such as Factory Pattern < Service Locator Pattern < Dependency Injection Pattern. Let’s break it down as below.

Considering some of the negative aspects of NoteManager implementation in each pattern,

in Factory Pattern we had,

  • Maintain static singleton access to NoteManager
  • Maintain static references to the INoteLoader and INoteReader service objects
  • Use NoteManager to access INoteLoader and INoteReader service objects
  • Resolve INoteLoader and INoteReader service objects manually

in Service Locator Pattern we had,

  • Maintain static singleton access to NoteManager
  • Resolve INoteLoader and INoteReader service objects manually

in Dependency Injection Pattern we had,

  • none of the above issues

So there you can clarify my claim of general improvements over each pattern, Factory Pattern < Service Locator Pattern < Dependency Injection Pattern.

Although that’s being said, the choice of Pattern to follow is totally up to you and your requirements. As an example something like Factory Pattern or Service Locator Pattern would be good enough for a small scale projects and Dependency Injection would be perfect for large scale projects with heavy MVVM based apps which uses a lot of service dependencies and so on.

Conclusion?

So I hope my demonstration of each of the patterns and how to implement them properly in a Xamarin Forms project solution for the same app concept, may have helped you in deciding which patterns to be used in any given scenario, which uses cross-platform dependencies.

Oh once again, You may find the complete solution up on my Github repo: https://github.com/UdaraAlwis/XFCPMobilePatterns

Go ahead and play around with the app and check out how each pattern is used in the MyNotes App scenario! 😉

Cheers everyone! 😀

A Keyboard disabled Entry control in Xamarin Forms?

A Xamarin Forms Entry Control without a keyboard? So when the user clicks on the Entry, the keyboard wouldn’t pop up? Yep, that’s what I’m talking about yo!

Oh sweet! So that I could use my custom keyboard or key buttons to enter values into it without the keyboard popping over and covering up the view? Oh yeah! that’s awesome! 😀

So it all began..

There was this one time where I was asked to implement a page which had an Entry with a bunch of custom buttons in the page, which would insert their specific values into the Entry controls when they’re clicked.
But if the User somehow clicked on the Entry, the Keyboard shouldn’t pop up and hover over the custom keyboard. And keep on mind the Entry field or the whatever alternative text editor view should be exactly similar to an entry looks and feel! 😮

Why such a requirement you ask? Imagine an text field which has limited or custom character inputs or a security code input field, where you want to have a custom keyboard on the view without using the default system keyboard for security reason, and many more. 🙂

Alternatives?

You could say, use a Label control where you would append its text value upon the custom key button clicks.
But the problem is, Label control doesn’t have the looks and feel of an Entry control, and it would be a big hassle to customize it to look as an Entry. Also from the performance aspect as well, since it will surely require custom rendering approach. 😦

Then you might say use the Keyboard dismissal service which I posted last time in my blog, and call up on it every time the user clicks on the Entry? But nope, that would look extremely distracting while the keyboard keep on popping up and down when the User clicks on the Entry every time.

So the solution?

So the only solution here is to have a Custom Entry control which doesn’t allow the popping up of the keyboard, or in other words, an Entry which has no Keyboard attachment up on focus.  😉

This is obviously the easiest and the fastest solution to execute, since we already got the Entry’s generic look and feel, along with all the behavior, except for the on Focus Keyboard attachment behavior. 😀

^there you go 😉

How could we do this?

Alright since we are going to customize our Entry control, we need to drill down to native levels of the actual Entry’s control rendering.

The Android EditText control that associates with the Xamarin Forms Entry’s has a property called ShowSoftInputOnFocus property which allows you to disable Keyboard attachment behavior upon focus for the EditText.

Then for iOS UITextField control that associates with the Xamarin Forms Entry’s has a property called InputView property which allows you to disable the Keyboard attachment by assigning it to an empty UIView object.

So we are going to use those native properties to implement this awesomeness! 😀

Coding it is!

First of all create a Custom Entry control by sub-classing it.

namespace WhateverYourNamespace
{
    public class SoftkeyboardDisabledEntry : Entry
    {

    }
}

 

Let’s call it SoftKeyboardDisabledEntry, just for the kicks of it 😉 !

iOS Custom Renderer…

Alright let’s drill down to iOS renderering of our custom control.

[assembly: ExportRenderer(typeof(SoftkeyboardDisabledEntry), typeof(SoftkeyboardDisabledEntryRenderer))]
namespace WhateverYourNamespace.iOS
{
    public class SoftkeyboardDisabledEntryRenderer : EntryRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
        {
            base.OnElementChanged(e);

            // Disabling the keyboard
            this.Control.InputView = new UIView();
        }
    }
}

 

Alright there we assign an empty UIView to the InputView property of the native control instance, which will replace Keyboard attachment at run time.

Android Custom Renderer…

Ok then comes the Android renderer, with a bit of work though.

[assembly: ExportRenderer(typeof(SoftkeyboardDisabledEntry), typeof(SoftkeyboardDisabledEntryRenderer))]
namespace WhateverYourNamespace.Droid
{
    public class SoftkeyboardDisabledEntryRenderer : EntryRenderer
    {
        protected override void OnElementChanged(ElementChangedEventArgs<Entry> e)
        {
            base.OnElementChanged(e);
        
            if (e.NewElement != null)
            {
                ((SoftkeyboardDisabledEntry)e.NewElement).PropertyChanging += OnPropertyChanging;
            }

            if (e.OldElement != null)
            {
                ((SoftkeyboardDisabledEntry)e.OldElement).PropertyChanging -= OnPropertyChanging;
            }

            // Disable the Keyboard on Focus
            this.Control.ShowSoftInputOnFocus = false;
        }

        private void OnPropertyChanging(object sender, PropertyChangingEventArgs propertyChangingEventArgs)
        {
            // Check if the view is about to get Focus
            if (propertyChangingEventArgs.PropertyName == VisualElement.IsFocusedProperty.PropertyName)
            {
                // incase if the focus was moved from another Entry
                // Forcefully dismiss the Keyboard 
                InputMethodManager imm = (InputMethodManager)this.Context.GetSystemService(Context.InputMethodService);
                imm.HideSoftInputFromWindow(this.Control.WindowToken, 0);
            }
        }
    }
}

 

So there we are disabling ShowSoftInputOnFocus property by setting it false, to disable Keyboard attachment event. 😀

But then you notice that we are subscribing to the IsFocused PropertyChanged event as well. This is because in Android if we move the focus to our Custom Entry from another Entry which already had the Keyboard attached, the Keyboard wouldn’t dismiss itself. So in order to dismiss the Keyboard in case if it was already popped up, we are calling the InputMethodManager to forcefully dismiss the Keyboard. 🙂  Well this is more of a fail safe for our object, but if you think you wouldn’t run into such a scenario as above then you could remove the additional fail safe bit. 😉

Try it out?

Alright to test this out, below is a cool demo I threw in together, which you could also find in my github repo: https://github.com/XFNoSoftKeyboadEntryControl

Here’s how to consume it in your XAML!

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

	<Label Text="Welcome to the Entry with disabled Keyboard!"
		   FontSize="22" FontAttributes="Bold" Margin="0,0,0,10"/>

	<Label Text="here is the normal Entry with Keyboard popping up on Focus"  TextColor="Gray" />
	<Entry Placeholder="Normal Entry Control..."/>

	<BoxView HeightRequest="0.7"  Margin="0,5,0,5"/>

	<Label Text="and here is our Entry with Keyboard disabled on Focus (but still editable)"  TextColor="Gray" />
	<local:SoftkeyboardDisabledEntry Placeholder="Keyboard disabled Entry Control..." x:Name="SoftkeyboardDisabledEntry" />
	
	
	<StackLayout VerticalOptions="EndAndExpand" Margin="0,0,0,10">
		<Label Text="So a simple custom keyboard may be? 😉 "  TextColor="Gray" />
		<StackLayout Orientation="Horizontal">
			<Button Text="A" Clicked="Button_OnClicked" WidthRequest="35" />
			<Button Text="B" Clicked="Button_OnClicked" WidthRequest="35" />
			<Button Text="C"  Clicked="Button_OnClicked" WidthRequest="35" />
			<Button Text="D"  Clicked="Button_OnClicked" WidthRequest="35" />
			<Button Text="E"  Clicked="Button_OnClicked" WidthRequest="35" />
			<Button Text="Clear All"  Clicked="ButtonClear_OnClicked" />
		</StackLayout>
	</StackLayout>

</StackLayout>

 

Next let’s add some Custom Key buttons to enter text to our Custom Entry with no Keyboard attached control! 😉

public partial class MainPage : ContentPage
{
	public MainPage()
	{
		InitializeComponent();
	}

	private void Button_OnClicked(object sender, EventArgs e)
	{
		SoftkeyboardDisabledEntry.Text 
                                  += ((Button) sender).Text;
	}

	private void ButtonClear_OnClicked(object sender, EventArgs e)
	{
		SoftkeyboardDisabledEntry.Text = "";
	}
}

 

that’s it.

Fire it up!

Hit that F5 and see the magic! 😀

 

WOOT! WOOT!

How cool is that eh! 😉

github repo: https://github.com/XFNoSoftKeyboadEntryControl

Enjoy and share.

Forcefully dismissing Keyboard in Xamarin Forms…

Wait… what? You want to forcefully dismiss your keyboard? A-B-S-O-L-U-T-E-L-Y!

Thanks to my experience in  working with high-expectation- seniors at my company, who demands me to push the limits of the Xamarin Forms Framework (frankly I love it, although it is kind of exhausting at times), I keep on sharing cool stuff which is quite out of the norm. And heyyy buckle up, since this is one of those instances where I pushed the limitations of Xamarin Forms! 😉

Once upon a time…

So there was this one time where I had to mimic a translucent layer on top of a login screen, where once the user enters username and password, I would simple capture a screenshot, blur it, and display as a blurred view on top of the page. But the problem there was as soon as user hits “Enter” on the keyboard, the screenshot will be captured but the keyboard would also be visible in the screenshot, since keyboard still stays up until a new layer is popped on top of the page (until the Entry’s focus is dismissed). 😦

Thereby the screenshot and the blurred view had the Keyboard visibility, which was pretty ugly, and my UX Lead wasn’t happy about it (perfectionists! lol).

“YOU MUST GET RID OF THE KEYBOARD VISIBILITY INSTANTLY, NO EXCUSE!”, demanded the UX Lead. 😮

Although this was no way possible out of the box from Xamarin Forms, I was asked to get rid of it one way or the other.

Nah I Didn’t give up!

You might think it’s just a matter of dismissing the focus of the Entry’s Completed event, but hell no it wasn’t! Because there was a specific delay from the Completed event to the keyboard dismissal event firing, which caused our screenshot capturing to capture the page with the Keyboard in view. 😮

So I knew I had to override or interrupt or short-wire the keyboard dismissal event myself forcefully. 😉

So after trying out many different solutions to get rid of the Keyboard visibility when the screenshot was captured, which ended up failing, I finally had the moment of “eureka!”.

le moment of eureka! 😀

Basically, what I did was to create a dependency service which would forcefully dismiss the keyboard, as in, push down the keyboard from which ever the current view of focus.

Sounds pretty simple eh? nah it wasn’t. lol

Up on the Entry’s Completed event I would first of all call up on my custom Keyboard dismissal service and then perform the screen capture and blurring view effect and so on. Which worked out pretty nicely!

Behold the results…

Yeah here’s something I built up to demonstrate the awesomeness of this hack!

How cool is that right? 😉

Besides the coolness, now you might ask what else could this be used for? Isn’t that obvious bro? 😛

Instances where,

  • you want to limit the user from entering text into an Entry after a given timeout?
  • may be dismiss the keyboard after a certain text length is reached?
  • instantly dismiss the keyboard straight from the ViewModel itself without having to go through a UI Event chain?

and so many other aspects, or it might as well be the same situation I had. 😉

Let me show you how it’s done…

So there’s no doubt we need to drill down to the native level when we try to push the limits of Xamarin Forms Framework, as usual.

In Android we could gain the access for the InputMethodManager which gives us the capability to hide the keyboard on demand.

And on iOS we use the UIApplication instance which gives us the access to the PresentedViewController property (current active ViewController), in return allowing us to call the EndEditing on its View to resign the first responder.

Finally I unite those two native calls via dependency service and be used from Xamarin Forms PCL level.

Here’s how to code it…

Blah blah blah.. yeah I talk too much when I’m enthusiastic about a hack I came across lol! 😀

First step create the interface for the keyboard dismissal service…

namespace WhateverYourNamespace
{
    /// <summary>
    /// Forcefully dismiss the keyboard
    /// </summary>
    public interface IForceKeyboardDismissalService
    {
        void DismissKeyboard();
    }
}

 

Now we could use this interface to do the native implementations which could be used via DependencyService of Xamarin Forms.

Next native hacking… or short circuiting you could say!

This is the time for native project level implementation of our service. Go ahead create your platform specific implementation of the IForceKeyboardDismissalService interface.

So for Android, we need to access the current Activity to access the InputMethodManager, for which we would use the Plugin.CurrentActivity library. So if you don’t have it, you might as well go ahead add that to your solution via nuget before implementing the below.

[assembly: Xamarin.Forms.Dependency(typeof(AndroidForceKeyboardDismissalService))]
namespace WhateverYourNamespace.Droid
{
    public class AndroidForceKeyboardDismissalService : IForceKeyboardDismissalService
    {
        public void DismissKeyboard()
        {
            InputMethodManager imm = InputMethodManager.FromContext(CrossCurrentActivity.Current.Activity.ApplicationContext);

            imm.HideSoftInputFromWindow(
                CrossCurrentActivity.Current.Activity.Window.DecorView.WindowToken, HideSoftInputFlags.NotAlways);
        }
    }
}

 

As you can see we are calling up the HideSoftInputFromWindow() method to dismiss the Keyboard via the InputMethodManager instance we retrieved.

Oh don’t forget to add the assembly attributes to register this for the Xamarin Forms DependencyService.

Then on iOS, we already have the singleton access to UIApplication where we are given access to the active PresentedViewController, which holds the instance for the current active view controller.

[assembly: Xamarin.Forms.Dependency(typeof(IosForceKeyboardDismissalService))]
namespace WhateverYourNamespace.iOS
{
    public class IosForceKeyboardDismissalService : IForceKeyboardDismissalService
    {
        public void DismissKeyboard()
        {
            UIApplication.SharedApplication.InvokeOnMainThread(() =>
            {
                var window = UIApplication.SharedApplication.KeyWindow;
                var vc = window.RootViewController;
                while (vc.PresentedViewController != null)
                {
                    vc = vc.PresentedViewController;
                }

                vc.View.EndEditing(true);
            });

        }
    }
}

 

Alright we are then calling the EndEditing() method from the current active View related to the active ViewController. There we are passing true as the parameter to let it know we mean business! 😛 lol uikit/uiview/1619630-endediting

Alright now time for the consumption of some cool code.

Consume it. (not literally) 😛

Here’s how you could use the above awesome service in Xamarin Forms.

DependencyService.Get<IForceKeyboardDismissalService>().DismissKeyboard();

 

That’s it!

Where’s the cool demo? 😮

Now don’t worry I shall not leave you hanging fellas!

You may be wondering where’s the cool implementation you saw at the beginning of the post… 😉
 

Here I have shared it on my github: UdaraAlwis/XFForcefulKeyboardDismiss

Alright, happy coding fellas! 😀

Enjoy and Share!

-Udara Alwis

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!