10 minute guide to building mobile apps in C#

AndroidiOS

1. Jump Right In

Welcome to Xamarin.Android! Once the installation is complete, follow these simple instructions to write and test your first Android C# code in minutes! You can also visit our Developer Center.

1.1. Running the Sample Application

First, let’s open the Tasky sample application, which can be done in either Visual Studio for Mac or Visual Studio. Tasky is a simple To-Do application that you can use to track tasks. It’s a cross-platform sample that shares its core code between Android and iOS and illustrates good cross-platform architectural design including data access, business logic, and native-UI elements.

The solution and project structure in the Solution pane shows all the files in the solution and should look familiar to any Modern IDE user. It consists of two projects containing a number of C# files.

If you cannot see the solution tree, choose View → Solution from the menu.

Introduction to Xamarin.Android Solution
Watch the video

Check that the Debug configuration is selected in the toolbar and choose Run → Debug from the menu or press Command + Return to start debugging with the Android Emulator.

Before an emulator can start you need to choose an Android Virtual Device (AVD) to use, as shown in these screens:

Once the emulator has started you can add some tasks to see how the application works - touch the Add Task button to begin!

Before looking at the code more closely, let’s revisit the solution and application architecture. There are two projects, which help facilitate a cross-platform solution when combined with Xamarin.Android:

  • TaskyAndroid - An Android application project containing the user-interface and application layer for Android devices.
  • Tasky.Core.Android - A Core library project which contains platform-independent code. This code is shared between different device platforms such as Android, iOS, and Windows Phone. Each platform has a different .csproj file (e.g. Tasky.Core.Android, Tasky.Core.iOS) but share the same C# code files.

1.2. Understanding the Architecture

The architecture and project structure of the Tasky application is shown in the following diagram:

The application is separated into Layers (each represented by a namespace), and each layer has a specific purpose:

  • User Interface - The screens, controls and data presentation code. In Xamarin.Android these classes are wrappers around the Android SDK. The user interface that you build looks, feels and performs like a native Java application.
  • App Layer - Custom classes to bind the business layer to the user interface, typically requiring platform specific features.
  • Business Layer - Business object classes and business logic.
  • Data Access Layer - Abstraction layer between the business logic and the data layer.
  • Data Layer - Low-level data persistence and retrieval; the Tasky sample uses a SQLite database binding.

2. Modifying Tasky

As it sits, Tasky lacks a basic feature of any decent task application: the ability to mark a task complete. We’re going to add that functionality by making the following modifications:

  1. Implement a new property on the Task object called Done.
  2. Add a mechanism in the UI to allow users to mark a task as completed.
  3. Change the home screen to display whether a task is completed.

We’re also going to spruce up the design of the application a bit by modifying the navigation bar style. After we've made all of these changes, here is how Tasky will look:

2.1. Implement a new property on the Task class

Add a new property to the Task class
Watch the video

Open the Task.cs file in Tasky.Core.Android and notice the class has the following property:

public bool Done { get; set; }

Tasky uses ADO.NET to store and retrieve data using the built-in SQLite database engine. All data operations can be performed with familiar SQL syntax and ADO.NET classes. Here's an example of how ADO Connection and Command objects can be used to access data stored in SQLite on an Android device:

using (var command = connection.CreateCommand ()) {
    command.CommandText = "SELECT [_id], [Name], [Notes], [Done] from [Items] WHERE [_id] = ?";
    command.Parameters.Add (new SqliteParameter (DbType.Int32) { Value = id });
    var reader = command.ExecuteReader ();
    if (reader.Read ())
    task = FromReader (reader);
    }

Now we need to modify the UI to support this change.

2.2. Add a corresponding property to the Task Details screen in the Application Layer

Add a done input control to the user interface
Watch the video

Now that we’ve modified our Task object, let’s modify the user interface to allow users to mark them as complete.

Screens in Xamarin.Android are typically defined by an XML layout file (with the .axml suffix) and one or more C# subclasses of Android.App.Activity that load that layout. We need to modify both the AXML and the C# to add the Done property to our user interface.

The Task Details layout is defined in the TaskDetails.axml file in the Resources/Layout folder. It already contains controls for the Task Name and Notes text inputs and labels, plus two buttons to Save or Delete the Task. To display the Task’s completion status we will add a Checkbox to this layout with the following XML after the NotesText control (which includes re-defining the layout_below property of both buttons):

<CheckBox
    android:id="@+id/chkDone"
    android:layout_below="@+id/NotesText"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Done" />
    <Button
    android:id="@+id/SaveButton"
    android:text="Save"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/chkDone"
    />
    <Button
    android:id="@+id/CancelDeleteButton"
    android:text="Cancel"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/SaveButton"
    />

The Task Details screen will now render a checkbox under the Notes input.

2.3. Sync changes made in the user interface back to the business object so they are saved

Displaying the Done checkbox control is only half of the data binding job - we must also load the current task’s Done status to set the control, and save the value if it changes. The Task Details Activity subclass is defined in the TaskDetailsScreen.cs file in the Screens folder.

The following changes are required to hook up the checkbox to the business object:

  • Define a new field in the class:
    CheckBox doneCheckbox;
  • Find the checkbox control and set its value in the OnCreate method:
    doneCheckbox = FindViewById<CheckBox>(Resource.Id.chkDone);
        doneCheckbox.Checked = task.Done;
  • Retrieve the value before persisting in the Save method:
    task.Done = doneCheckbox.Checked;

The updated task business object is then saved to the database via the Business Layer’s TaskManager class. This completes the changes to the Task Details screen - it will now display and save the new property we added to our business object.

2.4. Alter the Home screen so that the Done status is displayed in the list

Add a Done indicator to the list view
Watch the video

The final step is to display the completion status of each task on the home screen.

Each row in the task list is rendered via calls to the GetView method of TaskListAdapter.cs file in the Adapters folder. We need to alter the code to use a CheckedTextView and then set the Checked property. To do this replace the custom TaskListItem layout with the SimpleListItemCheck layout:

var view = (convertView ??
    context.LayoutInflater.Inflate(
    Android.Resource.Layout.SimpleListItemChecked,
    parent,
    false)) as CheckedTextView;

As we have changed the layout, delete the code describing the old Task List and replace it with code that matches the CheckedTextView properties

view.SetText (item.Name==""?"<new task>":item.Name, TextView.BufferType.Normal);
    view.Checked = item.Done;

The application now looks like this – the task completion status is visible in the list and can be marked as Done on the Task Details screen using the checkbox control:

2.5. Apply some styling to customize the appearance of the application

Change the style with a colored title bar
Watch the video

So now Tasky is a bit more useful, but let’s spice it up a bit by modifying the style of the application bar. Let’s change its color to a nice blue.

To do this, add the following code to the HomeScreen.cs and TaskDetailsScreen.cs files in the OnCreate method, make sure that it goes after the SetContentView method:

View titleView = Window.FindViewById(Android.Resource.Id.Title);
    if (titleView != null) {
    IViewParent parent = titleView.Parent;
    if (parent != null && (parent is View)) {
    View parentView = (View)parent;
    parentView.SetBackgroundColor(Color.Rgb(0x26, 0x75 ,0xFF)); //38, 117 ,255
    }
    }

The Android.Views namespace will need to be included in this file, you can easily add it by right-clicking on the code and resolve using Android.Views

There are lots more styling changes you can make to an Android application, including hiding the application bar altogether and replacing it with your own custom view. Now the user interface looks like this:

Awesome, we’ve now played with our first application in Xamarin.Android. We’ve seen Visual Studio for Mac in action, and we built and tested an application in the emulator.


3. Next Steps

Great job! You're on your way to becoming an awesome mobile developer.

Now, we recommend going through our Android Getting Started Tutorial Series

  1. Hello, Android, where we’ll create an Android application from scratch.
  2. Hello, Multiscreen Applications tutorial which will introduce you to navigating between different screens.
  3. Next steps to becoming a Xamarin.Android programmer where you'll learn about device deployment, building Android user interfaces and much more!
  4. Join the community on Xamarin Forums.

You’ll soon have a solid understanding of Xamarin.Android programming and be building your own apps!