In the Hello, Android Quickstart, we built and ran our first Xamarin.Android application. Now it’s time to develop a deeper understanding of how Android applications work so we can build more sophisticated programs. In this guide we review the steps that we took in the Hello, Android walkthrough so that we can understand what we did, and begin to develop a fundamental understanding of Android application development.
We will touch upon the following topics:
This guide helps you develop the skills and knowledge required to build a single-screen Android application. After working through it, you should have an understanding of the different parts of a Xamarin.Android application and how they fit together.
Visual Studio is a powerful IDE from Microsoft. It features a fully integrated visual designer, a text editor complete with refactoring tools, an assembly browser, source code integration, and more. In this guide we'll learn to use some basic Visual Studio features with the Xamarin plug-in.
Visual Studio organizes code into Solutions and Projects. A Solution is a container that can hold one or more Projects. A Project can be an application (such as iOS or Android), a supporting library, a test application, and more. In our Phoneword app, we added a new Android Project using the Android Application template to the Phoneword Solution we created in the Hello, Android guide. Our Solution looked like this:
# Anatomy of a Xamarin.Android ApplicationLet’s get oriented with our Solution’s contents. On the right is the Solution Explorer, which contains the directory structure and all the files associated with our Solution:
We’ve created a Solution called Phoneword and placed our Android project – Phoneword_Droid – inside it. Let’s take a look at the items inside the Project:
| Folder | Purpose |
| References | Contains the assemblies required to build and run the application. If we expand the References directory, we'll see references to .NET assemblies such as System, System.Core, and System.Xml, as well as a reference to Xamarin's Mono.Android assembly. |
| Components | The Components directory houses ready-made features from the Xamarin Components store, a public marketplace for Xamarin code. For more information on Xamarin Components, refer to the Xamarin Components walkthrough. |
| Assets | Contains the files the application needs to run including fonts, local data files, and text files. Files included here are accessible through the generated Assets class. For more information on Android Assets, see the Xamarin Using Android Assets guide. |
| Properties | Contains the AndroidManifest.xml file that describes all the requirements for our Xamarin.Android application, including name, version number, and permissions. The Properties folder also houses AssemblyInfo.cs, a .NET assembly metadata file. It is good practice to fill this file with some basic information about your application. |
| Resources | Contains application resources such as strings, images, and layouts. We can access these resources in code through the generated Resource class. The Android Resources guide provides more details about the
Resources directory. The application template also includes a concise guide to Resources in the AboutResources.txt file. |
| Item | Purpose |
| drawable | The drawable directory houses drawable resources such as images and bitmaps. In the default template, the drawable directory houses the application icon file, Icon.png. |
| layout | The layout directory contains Android designer files (.axml) that define the user interface for each screen or Activity. The template creates a default layout called Main.axml. |
| values | This directory houses XML files that store simple values such as strings, integers, and colors. The template creates a file to store string values called Strings.xml. |
| Resource.designer.cs | Also known as the Resource class, this file is a partial class that holds the unique IDs assigned to each resource. It is automatically created by the Xamarin.Android tools and is regenerated as necessary. This file should not be manually edited, as Xamarin.Android will overwrite any manual changes. |
When we set the ID property of the TranslateButton, the Android designer maps the TranslateButton control to the `Resource` class and assigns it a *resource ID* of `TranslateButton`. This mapping of visual control to class makes it possible for us to locate and use the TranslateButton and other controls in our code. We’ll cover this in more detail when we break apart the code that powers our controls. All you need to know for now is that the code representation of a control is linked to the visual representation of the control in the designer via the Id property.
## Source View
Everything we define on the design surface gets translated into XML for Xamarin.Android to use. The Android designer provides a source view that contains the XML it generated from the visual designer. We can view the XML by switching to the Source panel in the lower left of the designer view, as illustrated by the screenshot below:
The XML source code should contain our Text (Large), Plain Text, and two Button elements.
For a more in-depth tour of the Android designer, refer to the Xamarin Android [Designer Overview](http://developer.xamarin.com/guides/android/user_interface/designer_overview/) guide.
We’ve covered the tools and concepts behind the visual part of our user interface. Next, let’s jump into the code that powers our user interface as we explore Activities and the Activity Lifecycle.
# Activities and the Activity Lifecycle
The Activity class contains the code that powers the user interface. The Activity is responsible for responding to user interaction and creating a dynamic user experience.
In this section we introduce the Activity class, discuss the Activity Lifecycle, and dissect the code that powers the user interface in our Phoneword application.
## Activity Class
Our Phoneword application has only one screen (Activity). The class that powers the screen is called `MainActivity` and lives in the MainActivity.cs file. The name `MainActivity` has no special significance in Android - although it’s convention to name the first Activity in an application " `MainActivity`", Android wouldn’t care if we named it something else.
If we open the MainActivity.cs file, we see that our `MainActivity` class is a *subclass* of the `Activity` class, and that the Activity is adorned with the [ActivityAttribute](http://androidapi.xamarin.com/index.aspx?link=T%3aAndroid.App.ActivityAttribute):
```
[Activity(Label = "Phoneword", MainLauncher = true, Icon = "@drawable/icon")]
public class MainActivity : Activity
{
...
}
```
The Activity Attribute registers the Activity with the Android Manifest, letting Android know that this class is part of the Phoneword application managed by this Manifest. The `Label` property sets the text to display at the top of the screen, and the `Icon` sets the image to display next to the text, as illustrated by the screenshot below:
[ ](Images/image44.png)
The `MainLauncher` property tells Android to display this Activity when the application starts up. This property becomes important as we add more Activities (screens) to our application in the [Hello, Android Multiscreen](http://developer.xamarin.com/guides/android/getting_started/hello,android_multiscreen) guide.
Now that we understand the basics of the `MainActivity`, let’s dive deeper into the Activity code by introducing the Activity lifecycle.
## Activity Lifecycle
In Android, Activities go through different stages of a *lifecycle* depending on their interactions with the user. Activities can be created, started and paused, resumed and destroyed, and so on. The Activity class contains methods that the system calls at certain points in the screen's lifecycle. The following diagram illustrates a typical life of an Activity, and some of the corresponding lifecycle methods:
[ ](Images/image45.png)
By overriding Activity lifecycle methods, we can control how the Activity loads, how it reacts to the user, and even what happens after it disappears from the device screen. For example, we can override the lifecycle methods in the diagram above to perform some important tasks:
- **OnCreate** – Create views, initialize variables, and do other prep work before the user sees the Activity. This method is called only once when the Activity is loaded into memory.
- **OnResume** – Perform any tasks that need to happen every time the Activity returns to the device screen.
- **OnPause** – Perform any tasks that need to happen every time the Activity leaves the device screen.
When we add custom code to a lifecycle method in the Activity, we *override* that lifecycle method’s *base implementation*. We tap into the existing lifecycle method, which has some code already attached to it, and we extend it with our own code. We call the base implementation from inside our method to make sure the original code runs before our new code. We’ll see an example of this in the next section.
The Activity Lifecycle is an important and complex part of Android, and we’re not going to dive into the details just yet. If you’d like to learn more about Activities after you finish the Getting Started series, we recommend reading the [Activity Lifecycle](http://developer.xamarin.com/guides/android/application_fundamentals/activity_lifecycle/) guide. For now, let’s focus on the first stage of the Activity Lifecycle, `OnCreate`.
## OnCreate
Android calls the Activity’s `OnCreate` method when it creates the Activity, before the screen is presented to the user. We can override the `OnCreate` lifecycle method to create views and prepare our Activity to meet the user:
```
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
// Additional setup code will go here
}
```
In our Phoneword app, the first thing we do in `OnCreate` is load the user interface we created in the Android designer. To load the UI, we call `SetContentView` and pass it the *resource layout name* for the layout file - our `Main.axml`. Our layout is located at `Resource.Layout.Main`:
```
SetContentView (Resource.Layout.Main);
```
When the `MainActivity` starts up, it will create a view based on the contents of the `Main.axml` file. Note that we’ve matched our layout name with our Activity name - *Main*.axml is the layout for *Main*Activity. This isn’t required from Android’s point of view, but as we begin to add more screens to the application, we’ll find this naming convention makes it easy for us to match the code file to the layout file.
Once the layout file is set, we can start looking up our controls. To look up a control, we call `FindViewById` and pass in the resource ID of the control:
```
EditText phoneNumberText = FindViewById(Resource.Id.PhoneNumberText);
Button translateButton = FindViewById(Resource.Id.TranslateButton);
Button callButton = FindViewById(Resource.Id.CallButton);
```
Now that we have a reference to the controls in the layout file, we can start programming them to respond to user interaction.
## Responding to User Interaction
In Android, the `Click` event listens for the user’s touch. In our app, we handled the `Click` event with a lambda, but we could have also used a delegate or a named event handler. Our final TranslateButton code resembled the following:
```
translateButton.Click += (object sender, EventArgs e) =>
{
// Translate user’s alphanumeric phone number to numeric
translatedNumber = Core.PhonewordTranslator.ToNumber(phoneNumberText.Text);
if (String.IsNullOrWhiteSpace(translatedNumber))
{
callButton.Text = "Call";
callButton.Enabled = false;
}
else
{
callButton.Text = "Call " + translatedNumber;
callButton.Enabled = true;
}
};
```
# Additional Concepts Introduced in Phoneword
The Phoneword application introduced several concepts not covered in this guide. These concepts include:
Change Button Text – We learned to change the text of a Button by editing that
Button’s Text property. For example, the following code changes the callButton’s text to "Call":
callButton.Text = "Call";
Enable and Disable Buttons – Buttons can be in an Enabled or Disabled state. A disabled
Button won’t respond to user input. For example, the following code disables the callButton:
<pre><code class=" syntax brush-C#">callButton.Enabled = false;</code></pre>
<p>For more information on buttons, refer to the <a href="http://developer.xamarin.com/guides/android/user_interface/form_elements/custom_button">Android Buttons guide</a>.</p>
</li>
<li><p><strong>Display an Alert Dialog</strong> – When the user presses the Call <span class="uiitem">Button</span>, our app shows an <em>Alert Dialog</em> with the option to place or cancel a call. To create an Alert Dialog, we used an Alert Dialog <em>Builder</em>. Our dialog consists of a <code>Neutral</code> button to place a call and a <code>Negative</code> button to cancels the call, as illustrated by the code below:</p>
<pre><code class=" syntax brush-C#">var callDialog = new AlertDialog.Builder(this);
callDialog.SetMessage("Call " + translatedNumber + "?"); callDialog.SetNeutralButton("Call",
delegate
{
// Create intent to dial phone
});
callDialog.SetNegativeButton("Cancel", delegate {});
// Show the alert dialog to the user and wait for response. callDialog.Show();
<li><p><strong>Launch Phone App with Intent</strong> – When we wired up the <code>CallButton</code>, we sent an <em>Intent</em> to launch the system phone app, passing in the telephone number we wanted to call, as illustrated by the code sample below:</p>
<pre><code class=" syntax brush-C#">var callIntent = new Intent(Intent.ActionCall);
callIntent.SetData(Android.Net.Uri.Parse("tel:" + translatedNumber)); StartActivity(callIntent);
Intents are covered in more depth in the Hello, Android Multiscreen guide. In that guide, we’ll learn to use Intents to launch other Activities (screens) and even other applications.
Both Xamarin Studio and Visual Studio provide many options for testing and deploying an application. This section covers debugging options, demonstrates testing applications on device, and introduces tools for creating custom app icons for different screen densities.
Sometimes issues in application code are difficult to diagnose. To help diagnose complex code issues, we could Set a Breakpoint, Step Through Code, or Output Information to the Log Window.
The emulator is a good start for deploying and testing an application, but users will not consume the final app in the emulator. We should test applications on a real device early and often.
Before an Android device can be used for testing applications, it needs to be configured for development. The Set Up Device for Development guide provides thorough instructions on getting a device ready for development.
Once the device is configured, we can deploy to it by plugging it in, selecting it from the Select Device dialog, and starting the application:
<a href="Images/Image033.png" class=" fancybox"><img src="Images/Image033.png"></a>
This will launch the application on the device:
Android devices come in different screen sizes and resolutions, and not all images look good on all screens. For example, here is a screenshot of a low-density icon on a high-density Nexus 5. Notice how blurry it is compared to the surrounding icons:
To account for this, it is good practice to add icons of different resolutions to the Resources folder. Android provides different versions of the drawable folder to handle images of different densities, including an ldpi version for low density, mdpi for medium, hdpi for high, and xhdpi and xxhdpi for very high density screens. Icons of varying sizes are stored in the appropriate drawable-* folders:
<a href="Images/Image030.png" class=" fancybox"><img src="Images/Image030.png"></a>
Android will pick the icon with the appropriate density:
Not everyone has a designer available to create the custom icons and launch images an app needs to stand out. Here are several alternate approaches to generating custom app artwork:
For more information about icon sizes and requirements, refer to the Android Resources guide.
Congratulations! You now have a solid understanding of the components of a Xamarin.Android application as well as the tools required to create it.
In the next tutorial in the Getting Started series, we'll extend our application to handle multiple screens as we explore more advanced Android architecture and concepts.