Click here to Skip to main content
14,116,626 members
Click here to Skip to main content
Add your own
alternative version

Tagged as


97 bookmarked
Posted 29 Mar 2012
Licenced CDDL

Build C# and .NET Mobile Apps with Xamarin Development for Android – Part I

, 29 Mar 2012
Rate this:
Please Sign up or sign in to vote.
Building Android application with Visual Studio C#

This article appears in the Third Party Products and Tools section. Articles in this section are for the members only and must not be used to promote or advertise products in any way, shape or form. Please report any spam or advertising.

Build C# and .NET Mobile Apps with Xamarin Development for Android – Part I

By: Shalom Keynan, Pat Tormey MVP


I have been requested from a longtime friend and head of New Hampshire .Net Users Group (Seacoast) Pat Tormey to take Xamarin software Mono for Android for a test drive. I was tasked to take a fresh approach and objective overview from a C# .Net developer who has no experience in phone or android development. We wanted to create a presentation “Hello New-Hampshire .Net User Group,” as a demo application that utilizes users existing experience in C# and visual studio and develop Android applications. Our objectives were to create a sample application that could be use as a building block and could be a good starting point. We wanted to know how much of our C# knowledge would be portable to Android development.

Using the code

There are many examples on the web but we decided to follow with the Getting Started from Xamarin online documentation; it included 5 easy steps that got me started. We found their examples very concise and helpful. Xamarin has examples to develop in MonoDevelop and Visual Studio 2010. Our recommendations are to follow there tutorials since they are a great starting point. We also browsed for video tutorials to improve my android development knowledge, we recommend on Pluralsight they are an excellent training website, if you don’t have a membership we strongly suggest to use them, at either case you can take advantage of their 10 days trial, it ‘s worth every minute.

Android Project Overview

Android applications start with an Activity which will typically have an “axml Layout” for display the Activity->Layout set are the basic unit of work constituting the display and functions supporting that display, which are clearly defined as the Model View Controller (MVC) pattern.

Values such as strings are cleanly abstracted out to a Values folder under Resources folder as a Value Attribute pair.
All Resources are abstracted out to a resource folder that maintains Layouts, images , values and icons through the Resource Designer,which maps the friendly name to an internal unique Id.
Neither the Xamarin MonoDevelop IDE nor the Visual Studio IDE support WYSIWYG development.
Both the MonDevelop and the Visual Studio IDE support deploying to an emulator configured to match your expected Android target machine.

Getting Started

After completing the lessons we created a demo application ShalomNHDN (Shalom is the Hebrew word for greeting), it includes basic stuff and few things to watch out as you go through the code and application.

After working your way through the getting started demo, we decided in this application to built a sample application with the the following:

  • Adding an Activity header
  • Launching the application with splash screen
  • Using the default Xaml screen or build the layout dynamically.
  • Starting activity as intent and pass data between activities
  • Using a Simple List
  • Using a more Advance List – an example that takes the list and format the list presentation (part II)

First you will notice that launching the application starts the emulator, deploy/update the package and launch the application. If you look at Android dashboard you will see the application name and application icon. These information configured by the line on the splash activity

[Activity(Label = "Shalom NHDN", MainLauncher = true
    ,Theme = "@style/Theme.SplashNHDN", NoHistory = true
    , Icon = "@drawable/MyIcon")]

Label is the text under the icon and the icon located in Resources\Drawable\directory. The default icon is 72x72 pixels and is icon.png. You can use either PNG or GIF files and you can find more icons at website. Note: 64x64 size icons are good fit (animated gifs don’t seem to work).
The NHDN application launches with the SplashActivity ( MainLauncher = true ) and uses the default theme (Theme= "@style/Theme.SplashNHDN"). The theme located in the resource\values directory and points to an image nhdnsplash.png file(480x480 pixels).

    <style name="Theme.SplashNHDN" parent="android:Theme">
        <item name="android:windowBackground">@drawable/nhdnsplash</item>

We use the following to start the next activity

protected override void OnCreate(Bundle bundle)
            // Start our real activity

Phone Application ScreenSplash Activity

The first Activity (Screen) layout defined in two ways. You can use the axml layout or build the screen layout dynamically.

Using AXML file

//Uses aXml template and display items
     // Set our view from the "main" layout resource
            // Get our button from the layout resource,
            // and attach an event to it
            Button button = FindViewById<Button>(Resource.Id.MyButton);
            TextView aLabel2 = FindViewById<TextView> (Resource.Id.helloLabel);
            button.Click += delegate
                button.Text = string.Format("{0} user clicks!", count++);
                aLabel2.Text = "Hello NHDN! " + count.ToString();

The layout on the screen will appear the same way as your XAML file.

Build screen layout dynamically

 //Create the user interface in code
               var layout = new LinearLayout(this);
               layout.Orientation = Orientation.Vertical;
               var aLabel = new TextView(this);
               //aLabel.Text = "Hello, NHDN for Android";  
               // Set label as Fix text or from resource file
               var aButton = new Button(this);
               ////Lambda way to delegate event
               //aButton.Click += (sender, e) =>
               //    aLabel.Text = "Hello from the button";
               aButton.Click += delegate(object sender, EventArgs e)
                aLabel.Text = string.Format("You clicked me {0} times "+
 DateTime.Now.ToString() , count++);
               var aButton1 = new Button(this);
               //aButton.Text = "Say Hello";
               aButton1.Text="Start Second Activity";
               aButton1.Click += delegate(object sender, EventArgs e)
                   aButton1.Text = string.Format("clicked {0} " 
+ DateTime.Now.ToString(), count++);
                //  StartActivity(typeof(SecondActivity));
        // start activity as intent and pass data between activities
                 var second = new Intent(this, typeof(SecondActivity));
                 second.PutExtra("ActivityData", "Data from FirstActivity: " + aLabel.Text);
Default AXML layoutDynamic layout

Passing data between screens

To pass data between screens use Intent and place the following code
Note the use explicit use of INTENT , which prepares the Activity for more information. You can start an Activity with an implicit INTENT if you are not passing data.

var second = new Intent(this, typeof(SecondActivity));
second.PutExtra("ActivityData", "Data from FirstActivity: " + aLabel.Text);

On the receiving screen

Note how INTENT is queried for data passed by the calling Activity.

//Get data from FirstActivity
var label = FindViewById<TextView> (Resource.Id.screen2Label);
label.Text = Intent.GetStringExtra("ActivityData") ?? "Data not available";

Transferring data between activities

First ActivitySecond Activity

Simple List

Loading simple list with XML, preferred loading XML data from resource file, ultimately you will want to consider getting data from a web service or from a local resource file. At this scenario we explore the method of loading data from a local resource file.
The simple list class implements ListActivity, thus ListView refers to the listview widget in the resource layout. We added a toast message on selected item click event.

[Activity(Label = "Simple List of Books - Activity")]
   public class SimpleListActivity : ListActivity
       protected override void OnCreate(Bundle bundle)
           // get list of books from xml file in your resource
           string[] books = Resources.GetStringArray(Resource.Array.books_array);
           ListAdapter = new ArrayAdapter<string>(this, Resource.Layout.list_item,  books);

           ListView.TextFilterEnabled = true;
           // add a listener to Item click
           ListView.ItemClick += delegate(object sender, ItemEventArgs args)
               // When clicked, show a toast with the TextView text
                Toast.MakeText(Application," Selected Item: "+ ((TextView)   args.View).Text,ToastLength.Short).Show();

Setting the screen layout through the AXML file

<?xml version="1.0" encoding="utf-8"?>





    android:background="#0066CC"  >
    <ListView android:id="@android:id/list"



Simple List Activity


Working with Android is very strait forward, you can maximize your C# knowledge and with Xamarin toolkit for Visual Studio you are not far from having your first application up and running.

References – useful Links;

The following are useful links for Android Development.


This article, along with any associated source code and files, is licensed under The Common Development and Distribution License (CDDL)


About the Author

Shalom Keynan
Software Developer (Senior)
United States United States
Experienced hands-on manager in leading technology strategies, architecting web based solutions and application management solutions. Extensive in-depth and hands-on knowledge in software development, databases, Internet and IT infrastructure, Quality Assurance, imaging and e-commerce solutions.

You may also be interested in...

Comments and Discussions

QuestionXamarin.Forms Pin
FaizanMubasher25-Dec-14 18:24
professionalFaizanMubasher25-Dec-14 18:24 
QuestionSolution File? Pin
TomReit25-Aug-14 1:27
memberTomReit25-Aug-14 1:27 
Questioncomment Pin
akubue bona25-Oct-13 11:52
memberakubue bona25-Oct-13 11:52 
Questionusing Xamrine Consume WCF Webservice Pin
ashish.shedge13-May-13 19:43
memberashish.shedge13-May-13 19:43 
AnswerRe: using Xamrine Consume WCF Webservice Pin
ThatsAlok29-May-13 21:54
memberThatsAlok29-May-13 21:54 
GeneralMy vote of 3 Pin
Member 99714769-Apr-13 15:47
memberMember 99714769-Apr-13 15:47 
GeneralRe: My vote of 3 Pin
ThatsAlok12-Jul-13 2:07
memberThatsAlok12-Jul-13 2:07 
GeneralMy vote of 2 Pin
Saeed Hashemi19-Oct-12 22:25
memberSaeed Hashemi19-Oct-12 22:25 
Questionphone call Pin
securigy15-Oct-12 8:44
membersecurigy15-Oct-12 8:44 
QuestionWhat about Dictionary<string,string>? How can I send a Dictionary from Android to a WCF/Web Service? Pin
devvvy11-Sep-12 15:12
memberdevvvy11-Sep-12 15:12 
AnswerRe: What about Dictionary<string,string>? How can I send a Dictionary from Android to a WCF/Web Service? Pin
ThatsAlok12-Jul-13 2:08
memberThatsAlok12-Jul-13 2:08 
GeneralMy vote of 1 Pin
nanducs23-Jul-12 0:18
membernanducs23-Jul-12 0:18 
QuestionCool Pin
HoshiKata18-Jul-12 8:16
memberHoshiKata18-Jul-12 8:16 
GeneralMy vote of 5 Pin
Farhan Ghumra18-Jun-12 19:04
memberFarhan Ghumra18-Jun-12 19:04 
QuestionThanks for sharing Pin
Patrick Kalkman29-Mar-12 20:05
memberPatrick Kalkman29-Mar-12 20:05 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web03 | 2.8.190518.1 | Last Updated 29 Mar 2012
Article Copyright 2012 by Shalom Keynan
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid