Introduction to cross platform development with Xamarin.

In this short introduction course you will build your first Xamarin application using Visual Studio, and develop an understanding of the fundamentals of developing Android, iOS and Windows Universal applications. You will create an application that calculates your body mass index (BMI). This course assumes that you already have an understanding of programming.

The final application looks like this:

Source code

https://github.com/Quirasoft/getting-started-with-xamarin

Requirements

Windows 10
Visual Studio 2017
macOS Sierra 10.12 or above
Xcode 8.3

Installing Xamarin – Windows 10

To install Xamarin, use the following steps:

  1. Download Xamarin as part of Visual Studio Community, Visual Studio Professional or Visual Studio Enterprise from the Visual Studio page. https://www.visualstudio.com/vs/
  2. Double-click the downloaded package to start the installation.
  3. Select the Mobile development with. NET workload from the installation screen.

  4. Click the install / modify button in the lower right corner to install Xamarin.
  5. Depending on the Visual Studio edition that you are installing, the total installation may take a while to complete.

Installing Xamarin – macOS

To install Xamarin use the following steps:

  1. Download Visual Studio for Mac from the Visual Studio page. https://www.visualstudio.com/vs/
  2. After downloading the installer package, click the VisualStudioInstaller.dmg file to mount the installer and then run it by double clicking the logo.
  3. Click on the icon to install Visual Studio.
  4. If you get a warning regarding a downloaded dmg file from the internet, ignore it and click Open.
  5. Select the platforms (Android, iOS and macOS) that you want to install and click on Install.
    &nbps;
    &nbps;
  6. When the installation has been completed, press Start Visual Studio or the Done button.

It is entirely possible to develop the same application on a Mac, but this course uses Visual Studio in Windows 10.

Create a new application

  1. After you launch Visual Studio, create a new project. Click File -> New -> Project.
  2. On the new project screen navigate to Visual Studio C# -> Cross-Platform -> Cross platform App. Enter a name for your app (in the screenshot below the app’s name is BMIApp), and click OK.
  3. Create a Blank App that uses Native UI Technology, and for the code sharing use Portable Class Library (PCL).

    Xamarin.Forms
    Cross platform user interfaces in the language XAMLNative
    Use the native user interface approach to create user interfaces for each platform independent.Shared Project
    Under Shared Project, the reference project will compile the common code and it enables you to use platform-specific functionalities.Portable Class Library (PCL)
    A Portable Class Library enables you to write common code that compiles into libraries for multiple platforms. You cannot use platform-specific functionalities.
  4. After you click Ok you will get another screen where you need to configure the Universal Windows Project. You can leave it on the default configuration.



  5. In the Solution Explorer you will see the project structure.
  6. If you cannot see the solution explorer, navigate to View -> Solution Explorer.

Building the Universal Windows app

Before you can build the application, you first need to enable the Developer mode on your Windows 10 machine. Navigate to Navigate to Start > Settings > Update & Security > For developers > Select Developer mode

There is a possibility that you get an error message that says that the developer mode package failed to install. You can ignore this message.

In Visual Studio, select the Startup project by selecting the project BMIApp.UWP (Universal Windows) and press the button Local Machine to debug the application.


If everything went well, your project will compile and you will see a blank screen.

Building the Android app

To build the Android application, select the project BMIApp.Android and press the button to launch the emulator, or use your own device. You will see a black screen with the button Hello World, Click Me!

Building the iOS app

In Visual Studio, select the Startup project by selecting the project BMIApp.iOS. Before you can build the project, Visual Studio needs to connect to your Mac. Click on the monitor icon to open the Xamarin Mac Agent. On this screen, you first need to add the IP address of your Mac by pressing the Add Mac button. After entering your IP Address, click on add and connect to your Mac.

Select the device where the application will run on and you will see a white screen with the button Hello World, Click Me!

 

Develop BMI Formula

  1. Navigate to the BMIApp (Portable). Visual Studio automatically creates the file cs. Delete this file by right clicking and selecting delete.
  2. Create a new file by right clicking the project Add -> New Item
  3. Name the file Calculator and use the following code to calculate the Body Mass Index.
    
    
    namespace BMIApp
    {
        public class Calculator
        {
    		/// 
    <summary>
    		/// Calculate the body mass index (BMI) to evalute the body mass of a person.
    		/// </summary>
    
    		/// <param name="weight">The weight in kilograms</param>
    		/// <param name="height">The height in meters</param>
    		/// <returns>The BMI of the person</returns>
            public static float CalculateBodyMassIndex(float weight,float height)
            {
                return weight / (height * height);
            }
        }
    }
    
    

    Develop Interface Universal Windows app

    1. Navigate to the BMIApp.UWP project.
    2. Double click the file MainPage.xaml to see the design and the xaml code.
    3. The following interface will be built for the BMI application.
    4. To easily create the interface, we will use the Toolbox view. If you cannot see the ToolBox view, navigate to View > Toolbox.
    5. We will use the following controls to develop the interface.
      Control Label Properties
      TextBlock Weight (kg)
      TextBlock Height (m)
      TextBlock BMI
      TextBox Name = InputWeight

      InputScope = Digits

      TextBox Name = InputHeight

      InputScope = Digits

      TextBox Name = OutputResult

      IsReadOnly = true / checked

      Button Calculate Name = ButtonCalculate
    6. To select the control, select it and click on the canvas to place it.
    7. To change the properties of the control, go to the properties view. If you cannot see the properties view, navigate to View -> Properties Window.
    8. To automatically add a click handler, you need to double click the button Calculate in the design viewer. It will create the method ButtonCalculate_Click.
    9. To see the event, navigate to the properties window and select the toolbox icon (you will see a lighting icon). By clicking that icon, you will see all the events for that control.
    10. Navigate to the MainPage.xaml.cs file by clicking on the arrow MainPage.xaml.
    11. To make the code easier to read, there is no error checking included.
      using Windows.UI.Xaml;
      using Windows.UI.Xaml.Controls;
      
      namespace BMIApp.UWP
      {
          public sealed partial class MainPage : Page
          {
              public MainPage()
              {
                  this.InitializeComponent();
              }
      
              private void ButtonCalculate_Click(object sender, RoutedEventArgs e)
              {
                  var weight = float.Parse(this.InputWeight.Text);
                  var height = float.Parse(this.InputHeight.Text);
      
                  var result = Calculator.CalculateBodyMassIndex(weight, height);
      
                  this.OutputResult.Text = result.ToString();
              }
          }
      }
      
      
    12. To test the application, press the Debug button and fill in your weight and height and press the calculate button to calculate your BMI.

    Develop Interface Android app

    1. Navigate to the project BMIApp.Android
    2. Double click the file Main.xaml in Resources > layout
    3. First remove the button “Hello World, Click Me!” by pressing right click and delete.
    4. The following interface will be built for the BMI application.
    5. To easily create the interface, we will use the Toolbox view. If you cannot see the ToolBox view, navigate to View -> Toolbox
    6. We will use the following controls to develop the interface
      Control Label Properties
      Text (Large) Weight (kg)
      Text (Large) Height (m)
      Text (Large) BMI
      Number Decimal Id = @+id/InputWeight
      Number Decimal Id = @+id/InputHeight
      Text (Large) Id = @+id/OutputResult
      Button Calculate Id = @+id/ButtonCalculate
    7. To change the properties of the control, go to the properties view. If you cannot see the properties view, navigate to View -> Properties Window.
    8. Navigate to the MainActivity.cs file to implement the formula to calculate the BMI.
    9. To make the code easier to read, there is no error checking included.
      using Android.App;
      using Android.Widget;
      using Android.OS;
      
      namespace BMIApp.Droid
      {
          [Activity (Label = "BMIApp.Android", MainLauncher = true, Icon = "@drawable/icon")]
      	public class MainActivity : Activity
      	{
      		protected override void OnCreate (Bundle bundle)
      		{
      			base.OnCreate (bundle);
      
      			// Set our view from the "main" layout resource
      			SetContentView (Resource.Layout.Main);
      
      			// Get our button from the layout resource,
      			// and attach an event to it
      			Button button = FindViewById&amp;amp;amp;amp;amp;lt;Button&amp;amp;amp;amp;amp;gt; (Resource.Id.ButtonCalculate);
      			
      			button.Click += delegate {
      
                      var weight = float.Parse(FindViewById&amp;amp;amp;amp;amp;lt;EditText&amp;amp;amp;amp;amp;gt;(Resource.Id.InputWeight).Text);
                      var height = float.Parse(FindViewById&amp;amp;amp;amp;amp;lt;EditText&amp;amp;amp;amp;amp;gt;(Resource.Id.InputHeight).Text);
      
      
                      var result = Calculator.CalculateBodyMassIndex(weight, height);
      
                      FindViewById&amp;amp;amp;amp;amp;amp;amp;amp;amp;lt;TextView&amp;amp;amp;amp;amp;amp;amp;amp;amp;gt;(Resource.Id.OutputResult).Text = result.ToString();
      
                  };
      		}
      	}
      }
      
    10. To test the application, press the Debug button and fill in your weight and height and press the calculate button to calculate your BMI.

    Develop Interface iOS app

    1. Navigate to the project BMIApp.iOS
    2. For iOS we are going to create the interface through code. The reason for this is that Xcode interface builder does not always work correctly.
    3. Double click the file Main.storyboard and delete all the controls that you see.

    4. Navigate to ViewController.cs
    5. Here we are going to declare the variables that we are going to use.
      private UIButton ButtonCalculate;
      private UILabel LabelWeight;
      private UILabel LabelHeight;
      private UILabel LabelBMI;
      private UITextField InputWeight;
      private UITextField InputHeight;
      private UITextField OutputResult;
      
    6. We will create a method “CreateViews” to create our user interface views.
      private void CreateViews()
      {
      	this.ButtonCalculate = new UIButton(UIButtonType.System);
      	this.ButtonCalculate.SetTitle("Calculate", UIControlState.Normal);
      	this.ButtonCalculate.HorizontalAlignment = UIControlContentHorizontalAlignment.Left;
      	this.Add(this.ButtonCalculate);
      
      	this.LabelWeight = new UILabel();
      	this.LabelWeight.Text = "Weight (kg)";
      	this.Add(this.LabelWeight);
      
      	this.LabelHeight = new UILabel();
      	this.LabelHeight.Text = "Height (m)";
      	this.Add(this.LabelHeight);
      
      	this.LabelBMI = new UILabel();
      	this.LabelBMI.Text = "BMI";
      	this.Add(this.LabelBMI);
      
      	this.InputWeight = new UITextField();
      	this.InputWeight.Layer.CornerRadius = 5;
      	this.InputWeight.BorderStyle = UITextBorderStyle.RoundedRect;
      	this.InputWeight.KeyboardType = UIKeyboardType.DecimalPad;
      	this.Add(this.InputWeight);
      
      	this.InputHeight = new UITextField();
      	this.InputHeight.BorderStyle = UITextBorderStyle.RoundedRect;
      	this.InputHeight.KeyboardType = UIKeyboardType.DecimalPad;
      	this.Add(this.InputHeight);
      
      	this.OutputResult = new UITextField();
      	this.OutputResult.BorderStyle = UITextBorderStyle.RoundedRect;
      	this.OutputResult.Enabled = false;
      	this.Add(this.OutputResult);
      }
      
    7. We will use constraints to correctly position the layout of the views. With constraints, you can make the layout compatible for different screens.
    8. In the method SetupContraints we can declare our constraints. We need to set the property “TranslatesAutoresizingMaskIntoConstraints” to false to manually position the control.
      private void SetupConstraints()
      {
      	this.LabelWeight.TranslatesAutoresizingMaskIntoConstraints  = false;
      	this.InputWeight.TranslatesAutoresizingMaskIntoConstraints  = false;
      	this.LabelHeight.TranslatesAutoresizingMaskIntoConstraints  = false;
      	this.LabelBMI.TranslatesAutoresizingMaskIntoConstraints     = false;
      
      	this.InputHeight.TranslatesAutoresizingMaskIntoConstraints      = false;
      	this.ButtonCalculate.TranslatesAutoresizingMaskIntoConstraints  = false;
      	this.OutputResult.TranslatesAutoresizingMaskIntoConstraints     = false;
      
      	NSLayoutConstraint.ActivateConstraints(new NSLayoutConstraint[] {
      
      		this.LabelWeight.TopAnchor.ConstraintEqualTo(this.View.TopAnchor, 50),
      		this.LabelWeight.LeftAnchor.ConstraintEqualTo(this.View.LeftAnchor, 20),
      		this.LabelWeight.WidthAnchor.ConstraintEqualTo(100),
      
      		this.InputWeight.TopAnchor.ConstraintEqualTo(this.LabelWeight.TopAnchor, 0),
      		this.InputWeight.LeftAnchor.ConstraintEqualTo(this.LabelWeight.RightAnchor, 10),
      		this.InputWeight.RightAnchor.ConstraintEqualTo(this.View.RightAnchor, -20),
      
      		this.LabelHeight.TopAnchor.ConstraintEqualTo(this.LabelWeight.BottomAnchor, 20),
      		this.LabelHeight.LeftAnchor.ConstraintEqualTo(this.LabelWeight.LeftAnchor, 0),
      		this.LabelHeight.WidthAnchor.ConstraintEqualTo(this.LabelWeight.WidthAnchor),
      
      		this.InputHeight.TopAnchor.ConstraintEqualTo(this.LabelHeight.TopAnchor, 0),
      		this.InputHeight.LeftAnchor.ConstraintEqualTo(this.InputWeight.LeftAnchor,0),
      		this.InputHeight.RightAnchor.ConstraintEqualTo(this.InputWeight.RightAnchor, 0),
      
      		this.ButtonCalculate.TopAnchor.ConstraintEqualTo(this.InputHeight.BottomAnchor, 20),
      		this.ButtonCalculate.LeftAnchor.ConstraintEqualTo(this.InputHeight.LeftAnchor, 0),
      		this.ButtonCalculate.RightAnchor.ConstraintEqualTo(this.InputHeight.RightAnchor,0),
      	  
      		this.LabelBMI.TopAnchor.ConstraintEqualTo(this.ButtonCalculate.BottomAnchor, 20),
      		this.LabelBMI.LeftAnchor.ConstraintEqualTo(this.LabelHeight.LeftAnchor, 0),
      		this.LabelBMI.WidthAnchor.ConstraintEqualTo(this.LabelWeight.WidthAnchor),
      
      		this.OutputResult.TopAnchor.ConstraintEqualTo(this.LabelBMI.TopAnchor, 0),
      		this.OutputResult.LeftAnchor.ConstraintEqualTo(this.InputWeight.LeftAnchor, 0),
      		this.OutputResult.RightAnchor.ConstraintEqualTo(this.InputWeight.RightAnchor,0),
      		   
      	});
      
      }
      
    9. To calculate the BMI result, we will create a method called “SetupButtonCalculate” to implement the calculation.
      private void SetupButtonCalculate()
      {
      	// Perform any additional setup after loading the view, typically from a nib.
      	ButtonCalculate.AccessibilityIdentifier = "ButtonCalculate";
      	ButtonCalculate.TouchUpInside += delegate {
      
      		var weight = float.Parse(this.InputWeight.Text);
      		var height = float.Parse(this.InputHeight.Text);
      
      		var result = Calculator.CalculateBodyMassIndex(weight, height);
      
      		this.OutputResult.Text = result.ToString();
      
      	};
      }
      
    10. In the ViewDidLoad method we can call our methods to create the views and setup the constraints.
      public override void ViewDidLoad ()
      {
      	base.ViewDidLoad ();
      
      	this.CreateViews();
      
      	this.SetupConstraints();
      
      	this.SetupButtonCalculate();
      }
      
    11. To test the application, press the Debug button and fill in your weight and height and press the calculate button to calculate your BMI.

    Conclusion

    Congratulations on completing this introduction course! In this course you have learned:

    • How to install Visual Studio on Windows and Mac.
    • How to create a cross platform project.
    • How to create a cross platform library.
    • How to create a user interface.
    • How to write code for your application and connect it to your interface.

Let us know about your project

Let us guide you to realize your next big digital solution. We are your shortest path to a successful project that will make you smile. With our expertise, we work together on an enjoyable project with a smooth development process.

Start your project