Book Image

Mastering Xamarin UI Development

By : Steven F. Daniel
Book Image

Mastering Xamarin UI Development

By: Steven F. Daniel

Overview of this book

<p>Xamarin is the most powerful cross-platform mobile development framework. If you are interested in creating stunning user interfaces for the iOS and Android mobile platforms using the power of Xamarin and Xamarin.Forms, then this is your ticket.</p> <p>This book will provide you the practical skills required to develop real-world Xamarin applications. You will learn how to implement UI structures and layouts, create customized elements, and write C# scripts to customize layouts. You will create UI layouts from scratch so that you can tweak and customize a given UI layout to suit your needs by using Data Templates.</p> <p>Moving on, you will use third-party libraries – such as the Razor template engine that allows you to create your own HTML5 templates within the Xamarin environment – to build a book library Hybrid solution that uses the SQLite.Net library to store, update, retrieve, and delete information within a SQLite local database. You’ll also implement key data-binding techniques that will make your user interfaces dynamic, and create personalized animations and visual effects within your user interfaces using Custom Renderers and the PlatformEffects API to customize and change the appearance of control elements.</p> <p>At the end of this book, you will test your application UI for robust and consistent behavior and then explore techniques to deploy to different platforms.</p>
Table of Contents (19 chapters)
Mastering Xamarin UI Development
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Customer Feedback
Dedication
Preface

Creating the DistanceTravelledPage content page


In this section, we will begin building the user interface for our DistanceTravelledPage content page. This page is called when the user clicks on the Begin this Trail button from the WalksTrailPage content page, which will be used to display information about the chosen trail, as well as placing a pin placeholder within the Xamarin.Forms.Maps control and calculating the distance travelled, and time taken:

  1. Create a new ContentPage called DistanceTravelledPage as you did in the previous section.

  2. Next, ensure that the DistanceTravelledPage.cs file is displayed within the code editor and enter the following highlighted code sections:

            // 
            //  DistanceTravelledPage.cs 
            //  TrackMyWalks 
            // 
            //  Created by Steven F. Daniel on 04/08/2016. 
            //  Copyright © 2016 GENIESOFT STUDIOS. All rights reserved. 
            // 
            using Xamarin.Forms; 
            using Xamarin.Forms.Maps;
    
            using TrackMyWalks.Models; 
     
            namespace TrackMyWalks 
            { 
                public class DistanceTravelledPage : ContentPage 
                { 
  3. Then, update the DistanceTravelledPage method constructor to include the walkItem parameter for the chosen walk, as shown by the following highlighted code sections:

        public DistanceTravelledPage(WalkEntries walkItem)
        {
           Title = "Distance Travelled";
    
  4. Next, we declare a trailMap variable that will point to an instance of the Xamarin.Forms.Maps control to create a placeholder pin marker within the map control. Using the latitude and longitude coordinates, enter the following highlighted code sections:

            // Instantiate our map object
            var trailMap = new Map();
        // Place a pin on the map for the chosen walk type
        trailMap.Pins.Add(new Pin
        {
           Type = PinType.Place,
           Label = walkItem.Title,
           Position = new Position(walkItem.Latitude, walkItem.Longitude)
         });
         // Center the map around the list of walks entry's location
         trailMap.MoveToRegion(MapSpan.FromCenterAndRadius(new 
    Position(walkItem.Latitude, walkItem.Longitude), 
    Distance.FromKilometers(1.0)));
    
  5. Then, we declare a number of Label objects that contain our walkItem information, which has been passed from the WalkTrailPage content page so that we can trail related information. Enter in the following highlighted code sections:

        var trailNameLabel = new Label()
        {
            FontSize = 18,
            FontAttributes = FontAttributes.Bold,
            TextColor = Color.Black,
            Text = walkItem.Title
        };
        var trailDistanceTravelledLabel = new Label()
        {
            FontAttributes = FontAttributes.Bold,
            FontSize = 20,
            TextColor = Color.Black,
            Text = "Distance Travelled",
            HorizontalTextAlignment = TextAlignment.Center
        };
        var totalDistanceTaken = new Label()
        {
            FontAttributes = FontAttributes.Bold,
            FontSize = 20,
            TextColor = Color.Black,
            Text = $"{ walkItem.Distance } km",
            HorizontalTextAlignment = TextAlignment.Center
        };
        var totalTimeTakenLabel = new Label()
        {
            FontAttributes = FontAttributes.Bold,
            FontSize = 20,
            TextColor = Color.Black,
            Text = "Time Taken:",
            HorizontalTextAlignment = TextAlignment.Center
        };
        var totalTimeTaken = new Label()
        {
            FontAttributes = FontAttributes.Bold,
                FontSize = 20, 
                TextColor = Color.Black,
    
                Text = "0h 0m 0s",
    
                HorizontalTextAlignment = TextAlignment.Center
    
             };
    
  6. Next, we declare our walksHomeButton variable that inherits from the Button class and proceed to set up our click handler, which will be used to navigate our app to the main WalksPage content page when clicked. Enter the following highlighted code sections:

        var walksHomeButton = new Button
        {
            BackgroundColor = Color.FromHex("#008080"),
            TextColor = Color.White,
            Text = "End this Trail"
        };
         // Set up our event handler
         walksHomeButton.Clicked += (sender, e) =>
         {
             if (walkItem == null) return;
             Navigation.PopToRootAsync(true);
             walkItem = null;
          };
    
  7. Then, we define a ScrollView control that is part of the Xamarin.Forms.Core base class and proceed to add each of our form Button and Label fields to the StackLayout control. Enter the following highlighted code sections:

            this.Content = new ScrollView
           {
               Padding = 10,
               Content = new StackLayout
               {
                   Orientation = StackOrientation.Vertical,
                   HorizontalOptions = LayoutOptions.FillAndExpand,
                   Children = {
                       trailMap,
                       trailNameLabel,
                       trailDistanceTravelledLabel,
                       totalDistanceTaken,
                       totalTimeTakenLabel,
                       totalTimeTaken,
                       walksHomeButton
                    }
                  }
                 };
                }
               }
            } 
    
    

In the preceding code snippet, we began by importing our TrackMyWalks.Models class as we will be using this to extract the information passed in from our WalksPage. The Xamarin.Forms.Maps NuGet package is a cross-platform library that allows developers to display and annotate information within the map. We will be using this control to create a pin placeholder within the map control, along with additional details associated with the trail.

Next, we declare our trailMap variable that points to an instance of the Xamarin.Forms.Maps control and create a placeholder pin marker within the map containing the details for the chosen trail, then center in on the map to show the area for our walks location, derived by the latitude and longitude coordinates. We then declare and initialize a number of Label objects that contain the walkItem information that has been passed from the WalkTrailPage content page and declare our walksHomeButton variable that inherits from the Button class, then set up the Clicked event for the Button class, which will be used to navigate back to the TrackMyWalks when clicked.

Finally, we define a ScrollView control that is part of the Xamarin.Forms.Core base class, then add each of our form Button and Label fields to the StackLayout control.

In our next section, we will need to initialize the Xamarin.Forms.Maps NuGet package library within each of our platform-specific start up classes (for example, AppDelegate.cs for iOS and MainActivity.cs for Android). Let's take a look at how we can achieve this by following the steps below.

  1. Ensure that the AppDelegate.cs file is displayed within the code editor and enter the following highlighted code sections:

        // 
        //  AppDelegate.cs 
        //  TrackMyWalks 
        // 
        //  Created by Steven F. Daniel on 04/08/2016. 
        //  Copyright © 2016 GENIESOFT STUDIOS. All rights reserved. 
        // 
        using Foundation; 
        using UIKit; 
 
        namespace TrackMyWalks.iOS 
        { 
            [Register("AppDelegate")] 
            public partial class AppDelegate :  
        global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate 
            { 
                public override bool FinishedLaunching(UIApplication app,  
        NSDictionary options) 
                { 
                    global::Xamarin.Forms.Forms.Init(); 
                    Xamarin.FormsMaps.Init(); 
                    LoadApplication(new App()); 
                    return base.FinishedLaunching(app, options); 
                } 
            } 
        } 

In the preceding code snippet, we began by initializing our AppDelegate class to use the Xamarin.Forms.Maps library, by adding the Xamarin.FormsMaps.Init which initializes the Xamarin.Forms platform, so that our TrackMyWalks solution can use the maps. If this is omitted from this class, the DistanceTravelledPage content page will not display the map and will not work as expected.

Note

For more information on Xamarin.Forms.Maps library, as well as the various types of different classes available, please refer to the Xamarin developer documentation at https://developer.xamarin.com/api/namespace/Xamarin.Forms.Maps/ .