MobileAndroidIntroduction to Cross-Platform iOS/Android Apps with C# and Xamarin

Introduction to Cross-Platform iOS/Android Apps with C# and Xamarin

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Xamarin is a powerful toolset that brings the rich programming features of .NET and C# to Android and iOS. With Xamarin you are able to create full-featured Android and iOS applications with a shared code base working within a common programming environment. This is part one of a two-part article that walks you through the complete process of using Xamarin to create a simple cross-platform app with .NET and C# that runs on both Android and iOS. In part 1, I’ll introduce Xamarin, walk you through the process of creating a cross-platform code library with Xamarin, and guide you through the creation of the Android implantation of the cross-platform app. In part 2, I’ll cover the creation of the iOS implementation.

Getting Started

To get started you need to download and install Xamarin. Xamarin is available in a variety of editions: Starter, Indie, Business, and Enterprise. The specific edition you choose affects the level of features and support you receive. The most basic edition is the free Starter edition, which allows you to create simple applications using Xamarin’s development environment called Xamarin Studio. All other editions are available for purchase. The two higher end editions, Business and Enterprise, include advanced features such as integration with Microsoft Visual Studio. For more information on the features and cost of each edition, check out the Xamarin store.

The free Starter edition provides all the features you need to follow along with creating the app I describe in this article.

Setting up for Android

To develop Android applications with Xamarin you are free to use either Windows or OS X. The Xamarin.Android installation is very simple and straightforward. Parts of the Xamarin.Android build process leverage standard Android tools behind the scenes but the Xamarin installation takes care of setting up all of those tools for you. You can check out the Xamarin.Android Installation page for installation details.

Setting up for iOS

Xamarin.iOS uses the standard iOS development tools, but their usage is not quite as seamless as those for Android. Unlike Xamarin.Android, which automatically installs all required tools, Xamarin.iOS requires that you manually install the standard iOS development tools before installing Xamarin.iOS. The easiest way to do this is to install XCode from the Mac App Store. Once the XCode installation completes, you can then install Xamarin.iOS. The full Xamarin.iOS setup instructions are available on the Xamarin.iOS installation page.

The standard iOS development tools are only available for OS X; therefore, application development with Xamarin.iOS must be done with an OS X computer.

Note: If you are using the Visual Studio integration feature of the Business and Enterprise editions of Xamarin, you are able to edit and debug Xamarin.iOS code from within Visual Studio on a Windows computer but the actual build process still occurs on a Mac.

Xamarin Development Philosophy

To work effectively with Xamarin, one must understand the Xamarin cross-platform development philosophy. A philosophy I characterize as share what you can, don’t share what you can’t. This may sound strange so I’ll explain.

When building an app that targets multiple platforms, one quickly finds that there are many aspects of an app that are the same on all platforms but there are also many aspects that differ. Things like data validation, interacting with a backend service, or other aspects of an app’s business logic are likely to be the same across all target platforms. On the other hand, each platform has its own user interface model and unique platform features.

The Xamarin development approach embraces both the commonality and the differences. With Xamarin you can implement common application features in a shared library that you deploy with each platform’s app. These features will tend to use the .NET classes you may already be familiar with from working with .NET on Microsoft platforms.

You can also create platform specific code that leverages the unique features and capabilities of each platform. Xamarin makes this possible through the addition of .NET classes that are specific to each platform. For example, an application targeting Android uses the Android.App.Activity class to represent an app’s main window whereas an app targeting iOS might use the MonoTouch.UIKit.UIViewController class. Each of these classes provides full access to the features and capabilities of the individual platform.

This approach of having a mixture of shared code and platform specific code has a direct effect on how we structure our application projects. Creating a cross-platform Android and iOS app with Xamarin normally involves creating three types of projects.

  • A portable class library project that contains the shared code
  • An Android application project containing the Android specific code
  • An iOS application project containing the iOS specific code

Cross Platform Hello World

To demonstrate the cross-platform development experience, we’ll walk through the process of creating a simple app. The app will present a UI that provides the following functionality.

1. The user enters a string value into a text field

2. The user clicks a button

3. The app displays the count of upper case characters contained in the entered string within another text field

For example when the user enters the string Hello World, the app will display a message indicating that there are two upper case letters (H and W).

To create the Android and iOS applications that provide this functionality, you will need to create the following three projects.

  • MyXPlatformLib: Contains the business logic. In the case of this application, the business logic will consist of a class that accepts a string when constructed and exposes a property that returns the number of upper case letters in the string.
  • MyXPlatformAndroid: The Android implementation of the app.
  • MyXPlatformiOS: The iOS implementation of the app.

Organizing the Projects into Solutions

In this article we’ll walk through how to create the app using the development environment Xamarin includes with all editions of the product, Xamarin Studio. The best way to organize the Xamarin Studio solution depends on which operating systems you wish to use as your development environment.

Developing with OS X Only

If you plan to perform both the Android and iOS development using an OS X computer you can create a single solution containing all three projects.

Developing with Windows and OSX

If you plan to perform the Android development using a Windows computer and the iOS development using an OS X computer, you will need to create two separate solutions. The solution you create on the Windows computer will contain the MyXPlatformAndroid and MyXPlatformLib projects. The solution you create on the OS X computer will contain the MyXPlatformiOS and MyXPlatfomLib projects.

You will need to share the MyXPlatformLib project between the two computers. The best way to do this is using a source code control system such as Git. For simple projects like the one this article describes, you can use some type of shared drive technology like OneDrive, Google Drive, or Dropbox.

In this article, we’ll walk through the details of using a Windows computer for the Android development and OS X computer for the iOS development.

Note: Just a reminder that when using the Xamarin Business or Enterprise editions there’s a third option of doing all of your development work within Visual Studio on a Windows computer.

Creating the Android Application Solution

To get started we’ll first create a blank solution on the Windows computer. This is the solution that’ll contain the projects required to create the Android version of the application. To create the solution, do the following.

  • On the Windows computer, open Xamarin Studio
  • Open the New Solution dialog by selecting File from the Xamarin Studio menu, then selecting New followed by Solution…
  • In the New Solution dialog, choose Other in the left pane and Blank Solution in the right pane
  • Enter the solution name as MyXPlatformAndroid

The New Solution dialog should now appear similar to this figure.

BlankSolution-NewSolution
BlankSolution-NewSolution

Click OK to create the solution

With the blank solution created, you’re ready to start adding the individual projects.

Creating the Shared Library Project

The first project you’ll create is the shared library. To create the shared library project do the following.

  • Open the solution context menu by right-clicking on the solution name, MyXPlatformAndroid, in the Solution view
  • Open the New Project dialog by selecting Add from the context menu followed by Add New Project…
  • Select C# in the left pane of the dialog and Portable Library in the right pane
  • Enter the project name as MyXPlatformLib

The New Project dialog should now appear similar to this figure.

Portable Library-New Project
Portable Library-New Project

Click OK to create the project

Unlike a standard .NET library project, this project is not tied to a specific target platform. The created project is compatible with a variety of target platforms including Android, iOS, Windows Phone, Silverlight and others.

In this article we’re focusing on just iOS and Android but if, for example, Windows Phone was the platform you also wanted to support, this project could also be used within Visual Studio to create a Windows Phone app as well.

Adding Code

The newly created library project contains a class named MyClass. Double click on MyClass.cs in the Solution view to open the file in the editor. The class should appear similar to the following code listing.

using System;
 
 namespace MyXPlatformLib
 {
     public class MyClass
     {
         public MyClass ()
         {
         }
     }
 } 

You can use this existing MyClass class to provide the required logic but it is helpful to change the class name to something more meaningful. In the case of our application, the shared library provides reasonably simple string handling logic so change the name of this class to SillyString.

To change the class name, constructor name, and file name in a single step do the following.

  • Right-click on the class name, MyClass, in the source file to open the context menu
  • Open the Rename Class dialog by selecting Refactor from the context menu followed by Rename
  • In the Rename Class dialog enter SillyString as the New name value, check the Rename file that contains public class checkbox then click OK

To provide the required logic of accepting a string value, add a String member variable named originalValue to the class and modify the constructor to accept a string value and assign it to the member variable. The updated class should appear similar to the following code listing.

public class SillyString
 {
   String originalValue;

  public SillyString (String originalValue)
   {
     this.originalValue = originalValue;
   }
 }

In order to provide the business logic described earlier, the class needs to have a property that returns the number of upper case characters in the string. Providing this functionality is something you could do relatively simply using something like a for-loop but let’s use a more interesting approach. To demonstrate that Xamarin is providing the rich power of .NET we’ve become accustomed to over the years, let’s use Linq to determine the upper case character count.

To access the types in the System.Linq namespace, you’ll need to place a using statement for System.Linq at the beginning of the file.

using System.Linq;

Now, add the following UpperCount property to your SillyString class.

public int UpperCount
 {
   get

  { 
     var x = 
       from c in originalValue.ToCharArray()
       where Char.IsUpper (c)
       select c;
       

    return x.Count();
   }
 }

The property uses Linq to query the list of upper case characters from the string into a collection, x, on which the Linq Count method is called to find the number of upper case characters.

We now have our shared business logic in place for our application and this isn’t just some simple for-loop. We’re using rich .NET and C# features. The compiler is parsing a Linq expression, many of the Linq features are using extension methods, and the type of field, x, is determined through type inference. All of this code runs on both Android and iOS. That’s some pretty cool stuff.

Creating the Android Application Project

To create the actual Android app, we need to create an Android application project. To create the project, do the following.

  • Open the New Project dialog just as you did when creating the shared library project: right click on MyXPlatformAndroid in the Solution view, select Add followed by Add New Project…
  • Select Android in the left pane of the dialog and Android Ice Cream Sandwich Application in the right pane
    • Selecting Android Ice Cream Sandwich Application creates a project that targets devices running Android 4.0 or higher. Android 4.0 is a much richer platform than earlier versions and at the time of this writing, an app targeting Android 4.0 is compatible with nearly 80% of the Android devices in use
  • Enter the project name as MyXPlatformAndroid (same name as the solution)

The New Project dialog should now appear similar to this figure.

MyXPlatformAndroid NewProject
MyXPlatformAndroid NewProject

Click OK to create the project

The newly generated project contains a single screen Android application. We’ll now walk through how to add UI controls to the screen and tie in the logic from our shared library.

Adding Controls to the UI

To add controls to the Android UI you need to open the XML layout file in the Xamarin Studio layout designer. To open the layout file in the designer do the following.

  • In the Solution view expand the MyXPlatformAndroid project node
  • Under the MyXPlatformAndroid node expand the Resources node followed by the layout node

You should now see the Main.axml file as shown in the following figure.

MainAxml SolutionView
MainAxml SolutionView

Open Main.axml in the design view by double clicking on Main.axml in the Solution view.

The UI needs to have two text fields added: one above the button for the user to enter a string value and one below the button to display the count of upper case characters.

To add the first text field, do the following.

  • Locate the Text (Large) control in the Toolbox, which is located on the right side of Xamarin Studio.
  • Drag the Text (Large) control from the Toolbox and release it just above the button in the design view.
  • In the Properties tab, which is located on the lower right side of Xamarin Studio, locate the Id field in the widget section.
  • Set the Id field to the value @+id/textInput.
    • This Id value will be used to locate the control in your code.
  • Still in the Properties tab, locate the Text field and change the value to Input Field.

The Properties tab should now appear similar to the following figure.

Text Input Properties
Text Input Properties

To add the second text field, follow the same steps as you performed for the first text field with the following exceptions.

·         Place this second Text (Large) control below the button on the design view.

·         Set the Id field to the value @+id/textOutput.

·         Set the Text field value to Output Field.

The design view should now appear similar to the following figure.

Android Design View Controls Just Placed
Android Design View Controls Just Placed

Making the Input Field Editable

The characteristics of the text fields currently limit them to only displaying content; they are unable to accept input. We need to modify the characteristics of the first text field so that it is able to accept user input. There are a number of ways to modify the characteristics of the text fields, the easiest of which is to change the control type from TextView to EditText. EditText is a control that inherits from TextView and provides the necessary behavior for user input.

The easiest way to make this change is to switch from the layout design view to the layout XML view. You can change to the XML view by selecting the Source tab located at the bottom of the design view as shown in this figure.

Android Design View Change Layout To Source
Android Design View Change Layout To Source

Locate the first TextView element and change the element name to EditText. The updated XML should look similar to the following image.

Android Layout Edit Text Change
Android Layout Edit Text Change

You now have the application layout in place. The last thing you need to do is add the code to the Android project to link the UI to the shared library.

Making the Shared Library Available to the Android App Project

To use the shared library in the Android app project you must first add a reference to the shared library. To add the reference, do the following.

  • Open the context menu by right clicking on References under the MyXPlatformAndroid project in the Solution view.
  • Open the Edit References dialog by selecting Edit References from the context menu.
  • In the Edit References dialog select the Projects tab.
  • Select the checkbox next to MyXPlatformLib.
  • Click OK.

Using the Shared Library in the Android App

In this app all of the code related to the UI will be in the main application screen’s source file, MainActivity.cs. Locate MainActivity.cs in the Solution view and double click on it to open the file in the editor.

The first thing to do is add a using statement for MyXPlatformLib to the MainActivity.cs source file to make the types available without the need to namespace qualify them.

using MyXPlatformLib;

Bringing the Shared Library and Android App Together

The MainActivity class generated as part of the newly created project includes the code necessary to handle button clicks, which is shown here.

Button button = FindViewById<Button> (Resource.Id.myButton);
             
 button.Click += delegate {
   button.Text = string.Format ("{0} clicks!", count++); 

};

This default implementation simply increments and displays a counter. With some simple modifications to this code we can replace that code with our desired application behavior.

Delete the line that assigns to the button.text property and replace it with the code to retrieve a reference to the EditText control that contains the user input data. To do this use the FindViewById method passing in the ID value of the input text field, Resouce.Id.textInput.

EditText inputText = FindViewById<EditText>(Resource.Id.textInput);

With the inputText variable’s Text property you can access the value the user entered. With access to that value, you’re now ready to take advantage of the business logic contained in the shared library project.

Create an instance of the shared library’s SillyString class passing the entered text value then assign the value of the SillyString class’ UpperCount property to a local variable.

SillyString silly = new SillyString(inputText.Text);
 int upperCount = silly.UpperCount; 

Having applied the shared business logic, you can now simply access the output field using the FindViewById method, and display the number of uppercase characters.

TextView outputText = FindViewById<TextView>(Resource.Id.textOutput);
 outputText.Text = String.Format("{0} upper case chars", upperCount);

The complete button click handling code appears as shown in the following code listing.

button.Click += delegate {
  EditText inputText = FindViewById<EditText>(Resource.Id.textInput);

  SillyString silly = new SillyString(inputText.Text);
  int upperCount = silly.UpperCount;

  TextView outputText = FindViewById<TextView>(Resource.Id.textOutput);
  outputText.Text = String.Format({0} upper case chars”, upperCount);
};

You now have a complete Android application that takes advantage of the shared logic in the portable class library, MyXPlatformLib.

Testing the Android App

The easiest way to test your app is to use the Android emulator. Fortunately when you installed Xamarin, Xamarin automatically installed and setup some default Emulator configurations for you.

Starting the Emulator

Before you can run the app, you must first start the emulator. To access the dialog that starts the emulator, select Run from the Xamarin menu and then select Start Debugging. Xamarin will display the Select Device dialog, which appears similar to the following figure.

Select Device
Select Device

Scroll through the listed emulators until you find the emulator named MonoForAndroid_API_15. This is the emulator configured to run Android API Level 15, which is the API Level of Android 4.0 devices. Select MonoForAndroid_API_15 and then click the Start Emulator button near the bottom left edge of the dialog. The emulator launches and then goes through a booting process. The emulator booting process and startup may take several minutes the first time.

When the emulator startup completes, the emulator will look similar to the following image.

Emulator Startup
Emulator Startup

Use your mouse to drag padlock from the center of the screen to the right to unlock the emulator. The emulator is now ready to use.

Running the App

The Select Device dialog should still be open although it may be obscured by the emulator. On the Select Device dialog, again locate MonoForAndroid_API_15. MonoForAndroid_API_15 will probably be at the top of the list of devices now that it is running. With MonoForAndroid_API_15 selected, click the OK button to deploy the app to the device and start the app running.

You will again need to be patient because the initial deployment of an app may take a few minutes. The status of the deployment will display in the status window located on the Xamarin toolbar as shown in the following figure.

Installation Status
Installation Status

Verifying App Behavior

Once the app is started, perform the following steps to verify that the app behaves as expected.

  • Click in the Input Field, which will cause the emulator to display the soft keyboard.
  • Using the soft keyboard, click the backspace key to remove the Input Field text.
  • Still using the soft keyboard, enter a word or phrase of your choice such as Hello World.
  • Click the button.

The app will then display the number of upper case characters contained in the word or phrase you entered as shown in the following figure.

Android App Results
Android App Results

Congratulations! Your Android app is up and running correctly. You have successfully used Xamarin to create a shared library and Android application using .NET and C#.

Conclusion

In this article I introduced you to the Xamarin development toolset and the development philosophy of creating cross-platform apps with Xamarin. You learned how to create a portable class library project that allows you to share application code between the Android and iOS implementations of your app. You then learned how to create, test, and deploy the Android implementation of a cross-platform app.

Most of the work of creating your cross platform app is now done. In part 2 of this article, I’ll walk you through the final aspect of cross-platform development with Xamarin: how to create, test, and deploy the iOS app implementation.

About the Author

Jim Wilson is president of JW Hedgehog, Inc., a consulting firm specializing in solutions for the Android, iOS, and Microsoft platforms. He is Lead Mobile Developer for Spectafy, a start up empowering us all to make informed decisions through a combination of community and access to live, location-specific, crowd-sourced photos. Jim is also a regular contributor of mobility-related training materials to Pluralsight, a leading provider of online developer training. Jim’s latest book is “Creating Dynamic UI with Android Fragments”. Jim and his wife, along with several cats, live in Celebration, Florida (just 3 miles from Walt Disney World). Checkout Jim’s blog where he talks about a variety of mobile software development issues as well as the fun of life just 3 miles from the “House of Mouse”.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories