Xamarin September – Segment Control

Standard

Step 1

If not already, follow Setup and Start on how to Install and get Started with Visual Studio 2017 or in Windows 10 choose Start, and then from the Start Menu locate and select Visual Studio 2017.

xamarin-vs2017-home

Step 2

Once Visual Studio Community 2017 has started, from the Menu choose File, then New then Project…

xamarin-vs2017-file-new-project

Step 3

From New Project choose Visual C# from Installed, Templates then choose Cross Platform App (Xamarin) and then type in a Name and select a Location and then select Ok to create the Project

xamarin-vs2017-new-project

Step 4

Then in New Cross Platform App you need to select the Blank App Template then from UI Technology select Xamarin.Forms and in Code Sharing Strategy select Shared Project and then select Ok to continue

xamarin-vs2017-cross-platform

Step 5

The Xamarin Mac Agent will be displayed allowing connection to an Apple Mac but this can be dismissed with Close if running solely on Windows 10

xamarin-vs2017-mac-agent

Step 6

Then in New Universal Windows Project you need to select the Target Version to be Windows 10 Creators Update (10.0; Build 15063) and the Minimum Version to Windows 10 Creators Update (10.0; Build 15063) and then select Ok

xamarin-vs2017-target

Step 7

From the Menu choose Project, then Add New Item…

xamarin-vs2017-add-new-item

From the Add New Item choose Visual C# from Installed then choose Code then select Code File and then in the Name as Segment.cs and then select Add to add the file to the Project

xamarin-vs2017-segment

Step 9

Then in the Code View for Segment.cs the following should be entered:

using System;
using System.Collections.Generic;
using System.Linq;
using Xamarin.Forms;

namespace SegmentControl
{
    public class Segment : StackLayout
    {
        private readonly byte[][] table =
        {
            // a, b, c, d, e, f, g
            new byte[] { 1, 1, 1, 1, 1, 1, 0 }, // 0
            new byte[] { 0, 1, 1, 0, 0, 0, 0 }, // 1
            new byte[] { 1, 1, 0, 1, 1, 0, 1 }, // 2
            new byte[] { 1, 1, 1, 1, 0, 0, 1 }, // 3
            new byte[] { 0, 1, 1, 0, 0, 1, 1 }, // 4
            new byte[] { 1, 0, 1, 1, 0, 1, 1 }, // 5
            new byte[] { 1, 0, 1, 1, 1, 1, 1 }, // 6
            new byte[] { 1, 1, 1, 0, 0, 0, 0 }, // 7
            new byte[] { 1, 1, 1, 1, 1, 1, 1 }, // 8
            new byte[] { 1, 1, 1, 0, 0, 1, 1 }, // 9
            new byte[] { 0, 0, 0, 0, 0, 0, 0 }, // None
            new byte[] { 0, 0, 0, 0, 0, 0, 0 }, // Colon
        };
        private const int width = 5;
        private const int height = 25;

        private string _value;
        private int _count;

        public enum Sources
        {
            Value = 0,
            Time = 1
        }

        private AbsoluteLayout SetLayout(string name)
        {
            return this.Children.Cast<AbsoluteLayout>().FirstOrDefault(f => f.ClassId == name);
        }

        private Frame AddElement(string name, int left, int top, int width, int height)
        {
            Frame frame = new Frame()
            {
                ClassId = name,
                WidthRequest = width,
                HeightRequest = height,       
                BackgroundColor = Color.Accent,
                InputTransparent = true
            };
            Rectangle rect = new Rectangle()
            {
                Left = left,
                Top = top,
                Width = width,
                Height = height
            };
            frame.SetValue(AbsoluteLayout.LayoutBoundsProperty, rect);
            return frame;
        }

        private Frame SetElement(AbsoluteLayout layout, string name)
        {
            return layout.Children.Cast<Frame>().FirstOrDefault(f => f.ClassId == name);
        }

        private void AddSegment(string name)
        {
            AbsoluteLayout layout = new AbsoluteLayout()
            {
                Margin = new Thickness(2),
                ClassId = name
            };
            layout.Children.Add(AddElement($"{name}.a", width, 0, height, width));
            layout.Children.Add(AddElement($"{name}.h", width + width + width, width + width + width, width, width));
            layout.Children.Add(AddElement($"{name}.f", 0, width, width, height));
            layout.Children.Add(AddElement($"{name}.b", height + width, width, width, height));
            layout.Children.Add(AddElement($"{name}.g", width, height + width, height, width));
            layout.Children.Add(AddElement($"{name}.e", 0, height + width + width, width, height));
            layout.Children.Add(AddElement($"{name}.c", height + width, height + width + width, width, height));
            layout.Children.Add(AddElement($"{name}.i", width + width + width, height + width + width + width + width, width, width));
            layout.Children.Add(AddElement($"{name}.d", width, height + height + width + width, height, width));
            this.Children.Add(layout);
        }

        private void SetSegment(string name, int digit)
        {
            AbsoluteLayout layout = SetLayout(name);
            byte[] values = table[digit];
            SetElement(layout, $"{name}.a").Opacity = values[0];
            SetElement(layout, $"{name}.b").Opacity = values[1];
            SetElement(layout, $"{name}.c").Opacity = values[2];
            SetElement(layout, $"{name}.d").Opacity = values[3];
            SetElement(layout, $"{name}.e").Opacity = values[4];
            SetElement(layout, $"{name}.f").Opacity = values[5];
            SetElement(layout, $"{name}.g").Opacity = values[6];
            SetElement(layout, $"{name}.h").Opacity = digit > 10 ? 1 : 0;
            SetElement(layout, $"{name}.i").Opacity = digit > 10 ? 1 : 0;
        }

        private void GetLayout()
        {
            char[] array = _value.ToCharArray();
            int length = array.Length;
            List<int> list = Enumerable.Range(0, length).ToList();
            if (_count != length)
            {
                this.Children.Clear();
                foreach (int item in list)
                {
                    AddSegment(item.ToString());
                }
                _count = length;
            }
            foreach (int item in list)
            {
                string val = array[item].ToString();
                int digit = val == ":" ? 11 : int.Parse(val);
                SetSegment(item.ToString(), digit);
            }
        }

        public Segment()
        {
            this.Spacing = 0;
            this.Orientation = StackOrientation.Horizontal;
            Device.StartTimer(TimeSpan.FromMilliseconds(250), () =>
            {
                if(this.IsEnabled)
                {
                    if(Source == Sources.Time)
                    {
                        Value = DateTime.Now.ToString("HH:mm:ss");
                    }
                }
                return true;
            });
        }

        public static readonly BindableProperty SourceProperty =
        BindableProperty.Create<Segment, Sources>(p => p.Source, Sources.Value,
        BindingMode.Default, null, null);

        public Sources Source
        {
            get { return (Sources)GetValue(SourceProperty); }
            set { SetValue(SourceProperty, value); }
        }

        public string Value
        {
            get
            {
                return _value;
            }
            set
            {
                _value = value;
                GetLayout();
            }
        }
    }
}

Step 10

In the Solution Explorer select MainPage.xaml from the Shared Project

xamarin-vs2017-segment-mainpage-xaml

Step 11

From the Menu choose View and then Open

xamarin-vs2017-view-open

Step 12

The XAML View will be displayed, and in this remove the Label then between the ContentPage and /ContentPage elements, enter the following XAML:

<local:Segment HorizontalOptions="Center" VerticalOptions="Center" Source="Time"/>

It should appear as such:

xamarin-xaml-segment-control

Step 13

That completes the application, so from the Menu choose Build and then Build Solution

xamarin-vs2017-build-solution

Step 14

Then from the Menu choose Debug then Start Debugging to run the Application in the Android Emulator

xamarin-vs2017-debug-start

Step 15

Once started the Application should then appear in the Android Emulator displaying the time using the Segment Control

xamarin-android-run-segment-control

Step 16

To Exit the Application select Stop in Visual Studio

xamarin-vs2017-stop

Step 17

Another option is to run as a Universal Windows Application. From Solution Explorer select the Project ending with .UWP (Universal Windows), then from the Menu choose Project then Set as StartUp Project

xamarin-vs2017-project-startup

Step 18

Then again from the Menu choose Build and then select the Deploy option ending with .UWP

xamarin-vs2017-uwp-deploy

Step 19

Then once again from the Menu choose Debug then Start Debugging to run the Application in Windows 10

xamarin-vs2017-debug-start

Step 20

Once started the Application should then appear displaying the time using the Segment Control

xamarin-uwp-run-segment-control

Step 21

To Exit the Application select Stop in Visual Studio

xamarin-vs2017-stop

Step 22

Also if you have Mac with the Xamarin tools installed and have enabled and connected to the Xamarin Mac Agent. From Solution Explorer select the Project ending with .iOS, then from the Menu choose Project then Set as StartUp Project

xamarin-vs2017-project-startup

Step 23

Then once again from the Menu choose Debug then Start Debugging to run the Application for iOS

xamarin-vs2017-debug-start

Step 24

Once started the Application should then appear displaying the time using the Segment Control

Screenshots provided by Julia Boichentsova

Step 25

To Exit the Application select Stop in Visual Studio

xamarin-vs2017-stop

Thanks for Julia Boichentsova for helping with iOS screenshots

Creative Commons License

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s