VISUAL STUDIO   Windows Mac

Hello, Android: Quickstart

Introduction to Android development with Xamarin

PDF for offline use
Sample Code:

Let us know how you feel about this

Translation Quality


0/250

last updated: 2017-03

In this two-part guide, you will build your first Xamarin.Android application (using Xamarin Studio or Visual Studio) and develop an understanding of the fundamentals of Android application development with Xamarin. Along the way, you will be introduced to the tools, concepts, and steps required to build and deploy a Xamarin.Android application.

Hello, Android Quickstart

In this walkthrough, you will create an application that translates an alphanumeric phone number (entered by the user) into a numeric phone number and then calls that number. The final application looks like this:

Screenshot of app when it is complete

Requirements

To follow along with this walkthrough, you will need the following:

  • Windows 7 or later

  • Visual Studio 2013 Professional or later

  • The latest version of Xamarin Studio

  • OS X Yosemite or later (if you are using a Mac)

  • Windows 7 or later (if you are using a PC)

This walkthrough assumes that the latest version of Xamarin.Android is installed and running on your platform of choice. For a guide to installing Xamarin.Android, refer to the Xamarin.Android Installation guides. Before you get started, please download and unzip the Xamarin App Icons & Launch Screens set.

Configuring Emulators

If you are using Google's Android SDK emulator, we recommend that you configure the emulator to use hardware acceleration. Instructions for configuring hardware acceleration are available in Accelerating Android Emulators with HAXM.

If you are using the Visual Studio Android Emulator, Hyper-V must be enabled on your computer. For more information about configuring the Visual Studio Android Emulator, see System Requirements for the Visual Studio Emulator for Android.

Walkthrough

  1. Start Visual Studio:

    Start Visual Studio

  2. Click File > New > Project to create a new project:

    Start a new project

  3. In the New Project dialog, click the Blank App (Android) template. Name the new project Phoneword. Click OK to create the new project:

    New project is Phoneword

  4. After the new project is created, expand the Resources folder and then the layout folder in the Solution Explorer. Double-click Main.axml to open it in the Android Designer. This is the layout file for the app's screen:

    Open Main.axml

  5. From the Toolbox (the area on the left), enter text into the search field and drag a Text (Large) widget onto the design surface (the area in the center):

    Add large text widget

  6. With the Text (Large) control selected on the design surface, use the Properties pane to change the text property of the Text (Large) widget to Enter a Phoneword: as shown here:

    Set large text properties

  7. Drag a Plain Text widget from the Toolbox to the design surface and place it underneath the Text (Large) widget:

    Add plain text widget

  8. With the Plain Text widget selected on the design surface, use the Properties pane to change the id property of the Plain Text widget to @+id/PhoneNumberText and change the text property to 1-855-XAMARIN:

    Set plain text properties

  9. Drag a Button from the Toolbox to the design surface and place it underneath the Plain Text widget:

    Drag translate button to the design

  10. With the Button selected on the design surface, use the Properties pane to change the id property of the Button to @+id/TranslateButton and change the text property to Translate:

    Set translate button properties

  11. Drag a second Button from the Toolbox to the design surface and place it underneath the Translate button:

    Drag call button to the design

  12. With the new Button control selected on the design surface, use the Properties pane to change the id property of the Button to @+id/CallButton and change the text property to Call:

    Set call button properties

    Save your work by pressing CTRL+S.

  13. The next step is to add some code to translate phone numbers from alphanumeric to numeric. Add a new file to the project by right-clicking the Phoneword project in the Solution Explorer pane and choosing Add > New Item... as shown below:

    Add new item

  14. In the Add New Item dialog, select Visual C# > Code and name the new code file PhoneTranslator.cs:

    Add PhoneTranslator.cs

  15. This creates a new empty C# class. Insert the following code into this file:

    using System.Text;
    using System;
    namespace Core
    {
        public static class PhonewordTranslator
        {
            public static string ToNumber(string raw)
            {
                if (string.IsNullOrWhiteSpace(raw))
                    return "";
                else
                    raw = raw.ToUpperInvariant();
    
                var newNumber = new StringBuilder();
                foreach (var c in raw)
                {
                    if (" -0123456789".Contains(c))
                        newNumber.Append(c);
                    else {
                        var result = TranslateToNumber(c);
                        if (result != null)
                            newNumber.Append(result);
                    }
                    // otherwise we've skipped a non-numeric char
                }
                return newNumber.ToString();
            }
            static bool Contains (this string keyString, char c)
            {
                return keyString.IndexOf(c) >= 0;
            }
            static int? TranslateToNumber(char c)
            {
                if ("ABC".Contains(c))
                    return 2;
                else if ("DEF".Contains(c))
                    return 3;
                else if ("GHI".Contains(c))
                    return 4;
                else if ("JKL".Contains(c))
                    return 5;
                else if ("MNO".Contains(c))
                    return 6;
                else if ("PQRS".Contains(c))
                    return 7;
                else if ("TUV".Contains(c))
                    return 8;
                else if ("WXYZ".Contains(c))
                    return 9;
                return null;
            }
        }
    }

    Save the changes to the PhoneTranslator.cs file by clicking File > Save (or by pressing CTRL+S), then close the file.

  16. The next step is to add code to wire up the user interface by inserting backing code into the MainActivity class. In the Solution Explorer, find MainActivity.cs and open it:

    Open MainActivity.cs

  17. Begin by wiring up the Translate button. In the MainActivity class, find the OnCreate method. The next step is to add the button code inside OnCreate, below the base.OnCreate(bundle) and SetContentView (Resource.Layout.Main) calls. First, modify the template code so that the OnCreate method resembles the following:

    using System;
    using Android.App;
    using Android.Content;
    using Android.Widget;
    using Android.OS;
    
    namespace Phoneword
    {
        [Activity (Label = "Phoneword", 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);
    
                // New code will go here
            }
        }
    }
  18. Get a reference to the controls that were created in the layout file via the Android Designer. Add the following code inside the OnCreate method, after the call to SetContentView:

    // Get the UI controls from the loaded layout:
    EditText phoneNumberText = FindViewById<EditText>(Resource.Id.PhoneNumberText);
    Button translateButton = FindViewById<Button>(Resource.Id.TranslateButton);
    Button callButton = FindViewById<Button>(Resource.Id.CallButton);
  19. Add code that responds to user presses of the Translate button. Add the following code to the OnCreate method (after the lines added in the previous step):

    // Disable the "Call" button
    callButton.Enabled = false;
    
    // Add code to translate number
    string translatedNumber = string.Empty;
    
    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;
        }
    };
  20. Add code that responds to user presses of the Call button. Place the following code below the code for the Translate button:

    callButton.Click += (object sender, EventArgs e) =>
    {
        // On "Call" button click, try to dial phone number.
        var callDialog = new AlertDialog.Builder(this);
        callDialog.SetMessage("Call " + translatedNumber + "?");
        callDialog.SetNeutralButton("Call", delegate {
               // Create intent to dial phone
               var callIntent = new Intent(Intent.ActionCall);
               callIntent.SetData(Android.Net.Uri.Parse("tel:" + translatedNumber));
               StartActivity(callIntent);
           });
        callDialog.SetNegativeButton("Cancel", delegate { });
    
        // Show the alert dialog to the user and wait for response.
        callDialog.Show();
    };
  21. Finally, it's time give the application permission to place a phone call. App permissions can be edited in the Android Manifest. In the Solution Explorer, open the Android Manifest by double-clicking Properties under Phoneword, then select the Android Manifest page:

    Open the Android Manifest

    Under Required Permissions, enable the CALL_PHONE permission:

    Enable CALL_PHONE permission

  22. Save your work by selecting File > Save All (or by pressing CTRL-SHIFT-S) and build the application by selecting Build > Rebuild Solution (or by pressing CTRL-SHIFT-B). If the application compiles, you will get a success message in the Output window and in the bottom left corner of Visual Studio:

    Rebuild succeeded

    If there are errors, go through the previous steps and correct any mistakes until the application builds successfully. If you get a build error such as, Resource does not exist in the current context, verify that the namespace name in MainActivity.cs matches the project name (Phoneword) and then completely rebuild the solution. If you still get build errors, verify that you have installed the latest Xamarin.Android updates.

  23. You should now have a working application – it's time to add the finishing touches! In MainActivity.cs, edit the Label for the MainActivity. The Label is what Android displays at the top of the screen to let users know where they are in the application. At the top of the MainActivity class, change the Label to Phone Word as shown here:

    namespace Phoneword
    {
        [Activity (Label = "Phone Word", MainLauncher = true, , Icon = "@drawable/icon")]
        public class MainActivity : Activity
        {
            ...
        }
    }
  24. Next, set the application icon. First, download and unzip the Xamarin App Icons set. Next, expand the drawable folder under Resources and remove the existing Icon.png by right-clicking it and selecting Delete:

    Delete existing icon

    When the following dialog box is displayed, click OK:

    Delete icon dialog

  25. Next, right-click the drawable folder and select Add > Existing Item...:

    Add existing item

  26. From the selection dialog, navigate to the unzipped Xamarin App Icons directory and open the drawable folder. Select Icon.png and click Add:

    Select and add icon

  27. Next, add the rest of the Xamarin App Icons drawable- folders to the project. These folders provide different resolutions of the icon so that it renders correctly on different devices with different screen densities. In a File Explorer window, navigate to the unzipped Xamarin App Icons directory and select the drawable-* folders:

    Select drawable folders for copy

    Drag these folders onto the Resources folder in the Visual Studio Solution Explorer pane. These folders are now part of the project as shown in Solution Explorer on the right:

    Drag icon folders into Solution

  28. Specify the icon in the Android Manifest by choosing @drawable/Icon from the Application Icon drop-down menu:

    Specify application icon

  29. Finally, you can test your application by deploying it to an emulator. Before you send your app to an emulator or device, you must configure the app's minimum Android version so that it matches the Android version of your emulator or test device. In Visual Studio, open the Application page of Properties and set the API level in the Minimum Android to target drop-down menu. In the following, screen shot, the Minimum API level is set to Android 7.0 (API Level 24 - Nougat):

    Set API level to 24

    This setting is compatible with the virtual device that will be used in the next step.

  30. In the next screenshot, a custom virtual device called AVD-Nexus5-N (Android 7.0 - API 24) is chosen from the device drop-down menu. If no virtual devices are available in the drop-down menu, you must create and configure a virtual device via the Android AVD Manager as explained in Android SDK Emulator. Deploy the app by choosing the device from the drop-down menu and then clicking the green "play" arrow as shown here:

    Select device and start

    Visual Studio will copy files to this emulator before installing and launching the app.

  31. The screenshots below illustrate the Phoneword application running in the Android SDK Emulator. Clicking the Translate button updates the text of the Call button, and clicking the Call button causes the call dialog to appear as shown on the right:

    Phoneword running in emulator

  1. Launch Xamarin Studio from the Applications folder or from Spotlight. This opens the start page:

    Launch Xamarin Studio

  2. Click New Solution... to create a new project:

    Create a new project

  3. In the Choose a template for your new project dialog, click Android > App and select the Android App template. Click Next.

    Choose the Android App template

  4. In the Configure your Android app dialog, name the new app Phoneword and click Next:

    Name the project Phoneword

  5. In the Configure your new project dialog, leave the Solution and Project names set to Phoneword and click Create to create the project. Be sure to uncheck the checkbox for Xamarin Test Cloud (if the Xamarin Insights checkbox is shown, uncheck it as well):

    Create project

  6. After the new project is created, expand the Resources folder and then the layout folder in the Solution pad. Double-click Main.axml to open it in the Android Designer. This is the layout file for the screen:

    Open Main.axml

  7. Select the Hello World, Click Me! Button on the design surface and press the Delete key to remove it. From the Toolbox (the area on the right), enter text into the search field and drag a Text (Large) widget onto the design surface (the area in the center):

    Add large text widget

  8. With the Text (Large) widget selected on the design surface, you can use the Properties pad to change the Text property of the Text (Large) widget to Enter a Phoneword: as shown below:

    Set large text widget properties

  9. Next, drag a Plain Text widget from the Toolbox to the design surface and place it underneath the Text (Large) widget. Notice that you can use the search field to help locate widgets by name:

    Add plain text widget

  10. With the Plain Text widget selected on the design surface, you can use the Properties pad to change the Id property of the Plain Text widget to @+id/PhoneNumberText and change the Text property to 1-855-XAMARIN:

    Set plain text widget properties

  11. Drag a Button from the Toolbox to the design surface and place it underneath the Plain Text widget:

    Add a button

  12. With the Button selected on the design surface, you can use the Properties pad to change the Id property of the Button to @+id/TranslateButton and change the Text property to Translate:

    Configure as the translate button

  13. Next, drag a second Button from the Toolbox to the design surface and place it underneath the Translate button:

    Add a second button

  14. With the Button selected on the design surface, you can use the Properties pad to change the Id property of the Button to @+id/CallButton and change the Text property to Call:

    Configure as the call button

    Save your work by pressing ⌘ + S.

  15. Now, add some code to translate phone numbers from alphanumeric to numeric. Add a new file to the project by clicking the gear icon next to the Phoneword project in the Solution pad and choosing Add > New File...:

    Add a new file to the project

  16. In the New File dialog, select General > Empty Class, name the new file PhoneTranslator, and click New:

    The new file is named PhoneTranslator.cs

  17. This creates a new empty C# class for us. Remove all of the template code and replace it with the following code:

    using System.Text;
    using System;
    namespace Core
    {
        public static class PhonewordTranslator
        {
            public static string ToNumber(string raw)
            {
                if (string.IsNullOrWhiteSpace(raw))
                    return "";
                else
                    raw = raw.ToUpperInvariant();
    
                var newNumber = new StringBuilder();
                foreach (var c in raw)
                {
                    if (" -0123456789".Contains(c))
                        newNumber.Append(c);
                    else {
                        var result = TranslateToNumber(c);
                        if (result != null)
                            newNumber.Append(result);
                    }
                    // otherwise we've skipped a non-numeric char
                }
                return newNumber.ToString();
            }
            static bool Contains (this string keyString, char c)
            {
                return keyString.IndexOf(c) >= 0;
            }
            static int? TranslateToNumber(char c)
            {
                if ("ABC".Contains(c))
                    return 2;
                else if ("DEF".Contains(c))
                    return 3;
                else if ("GHI".Contains(c))
                    return 4;
                else if ("JKL".Contains(c))
                    return 5;
                else if ("MNO".Contains(c))
                    return 6;
                else if ("PQRS".Contains(c))
                    return 7;
                else if ("TUV".Contains(c))
                    return 8;
                else if ("WXYZ".Contains(c))
                    return 9;
                return null;
            }
        }
    }

    Save the changes to the PhoneTranslator.cs file by choosing File > Save (or by pressing ⌘ + S), then close the file. Ensure that there are no compile-time errors by rebuilding the solution.

  18. The next step is to add code to wire up the user interface by adding the backing code into the MainActivity class. Double-click MainActivity.cs in the Solution Pad to open it:

    Open MainActivity.cs

  19. Begin by wiring up the Translate button. In the MainActivity class, find the OnCreate method. Add the button code inside OnCreate, below the base.OnCreate(bundle) and SetContentView (Resource.Layout.Main) calls. Remove the template button handling code so that the OnCreate method resembles the following:

    using System;
    using Android.App;
    using Android.Content;
    using Android.Runtime;
    using Android.Views;
    using Android.Widget;
    using Android.OS;
    
    namespace Phoneword
    {
        [Activity (Label = "Phoneword", MainLauncher = true)]
        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);
    
                // Our code will go here
            }
        }
    }
  20. Next, a reference is needed to the controls that were created in the layout file with the Android Designer. Add the following code inside the OnCreate method (after the call to SetContentView):

    // Get our UI controls from the loaded layout:
    EditText phoneNumberText = FindViewById<EditText>(Resource.Id.PhoneNumberText);
    Button translateButton = FindViewById<Button>(Resource.Id.TranslateButton);
    Button callButton = FindViewById<Button>(Resource.Id.CallButton);
  21. Add code that responds to user presses of the Translate button by adding the following code to the OnCreate method (after the lines added in the last step):

    // Disable the "Call" button
    callButton.Enabled = false;
    
    // Add code to translate number
    string translatedNumber = string.Empty;
    
    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;
        }
    };
  22. Add code that responds to user presses of the Call button. Place the following code below the code for the Translate button:

    callButton.Click += (object sender, EventArgs e) =>
    {
        // On "Call" button click, try to dial phone number.
        var callDialog = new AlertDialog.Builder(this);
        callDialog.SetMessage("Call " + translatedNumber + "?");
        callDialog.SetNeutralButton("Call", delegate {
               // Create intent to dial phone
               var callIntent = new Intent(Intent.ActionCall);
               callIntent.SetData(Android.Net.Uri.Parse("tel:" + translatedNumber));
               StartActivity(callIntent);
           });
        callDialog.SetNegativeButton("Cancel", delegate { });
    
        // Show the alert dialog to the user and wait for response.
        callDialog.Show();
    };
  23. Finally, give the application permission to place a phone call. Open the project options by right-clicking Phoneword in the Solution pad and selecting Options:

    Open application permissions

    In the Project Options dialog, select Build > Android Application. In the Required Permissions section, enable the CallPhone permission:

    Enable the CallPhone permission

  24. Save your work and build the application by selecting Build > Build All (or by pressing ⌘ + B). If the application compiles, you will get a success message at the top of Xamarin Studio:

    Successful build

    If there are errors, go through the previous steps and correct any mistakes until the application builds successfully. If you get a build error such as, Resource does not exist in the current context, verify that the namespace name in MainActivity.cs matches the project name (Phoneword) and then completely rebuild the solution. If you still get build errors, verify that you have installed the latest Xamarin.Android and Xamarin Studio updates.

  25. Now that you have a working application, it's time to add the finishing touches! Start by editing the Label for MainActivity. The Label is what Android displays at the top of the screen to let users know where they are in the application. At the top of the MainActivity class, change the Label to Phone Word as shown here:

    namespace Phoneword
    {
        [Activity (Label = "Phone Word", MainLauncher = true)]
        public class MainActivity : Activity
        {
            ...
        }
    }
  26. Next, set the application icon. Open the downloaded and unzipped Xamarin App Icons set. Expand the drawable-hdpi folder under Resources and remove the existing Icon.png by right-clicking it and selecting Remove:

    Remove existing icon

    When the following dialog box is displayed, select Delete:

    Delete icon

  27. Next, right-click the drawable-hdpi folder and select Add > Add Files:

    Add files

  28. From the selection dialog, navigate to the unzipped Xamarin App Icons directory and open the drawable-hdpi folder. Select Icon.png:

    Select icon file

  29. In the Add File to Folder dialog box, select Copy the file into the directory and click OK:

    Copy the file to the directory

  30. Repeat these steps for each of the drawable- folders until the contents of the drawable- Xamarin App Icons folders are copied to their counterpart drawable- folders in the Phoneword project:

    Add drawable folders to Resources

    These folders provide different resolutions of the icon so that it renders correctly on different devices with different screen densities.

  31. Finally, test the application by deploying it to an Android emulator. In Xamarin Studio, select a virtual device (under Virtual Devices) and click the play button in the upper left corner:

    Select virtual device

    As shown in this screenshot, the Nexus 4 (KitKat) (API 19) virtual device was selected.

  32. After Xamarin Studio loads the application into the virtual device, the Phoneword app is automatically started. The screenshots below illustrate the Phoneword application running in an Android SDK emulator configured as a Nexus 5 running Lollipop. Clicking the Translate button updates the text of the Call button, and clicking the Call button causes the call dialog to appear as shown on the right:

    Phoneword running in emulator

Congratulations on completing your first Xamarin.Android application! Now it's time to dissect the tools and skills you have just learned. Next up is the Hello, Android Deep Dive.

Xamarin Workbook

If it's not already installed, install the Xamarin Workbooks app first. The workbook file should download automatically, but if it doesn't, just click to start the workbook download manually.