Getting Started with Xamarin Android

By September 11, 2013Android, C#, Xamarin
[Please see the Table of Contents for this series.]

I have embarked on a great adventure, full of trepidation and woe.  I have set out to learn to write Android applications using Xamarin though I confess to being no friend of Java, Android or cross-platform development (I worked on a cross-platform project (Mac and Windows) in the 1990’s, would you like to see my scars?)

To make this adventure more enjoyable, and to ensure that I don’t quake in fear and turn back at the sight of the first dragon, I have decided to take you along with me.  Buckle up.

The goal of Xamarin, as I understand it, is to allow you to reuse a significant portion of your logic across the  three supported platforms (iOS, Android and Windows Phone).  In addition, and this is most important to me, it allows you to develop Android (and iOS) applications using C# and (more or less) .NET – worlds I am familiar with and enjoy.

“Write once, run anywhere perfectly is a unicorn” – Nat Friedman CEO of Xamarin

Decisions, Decisions

The first decision I faced was iOS or Android or both.  This one was easy; it was made for me by my friends at Falafel.  Lance Bullock is already writing about iOS development with Xamarin, so I took on Android.

Second decision: develop in Visual Studio (my beloved work environment) or Xamarin Studio (the new contender).  For now, I’ll switch back and forth with an emphasis on trying to make Xamarin Studio work for me. No promises.

Hitting The Ground Running

It is a truism that if you are already a .NET developer, you hit Xamarin’s ground running.  You have access to much of the Base Class Library and you get to write in C#, complete with access to C#’s coolness such as LINQ, lambda expressions, reflection, thread pooling, asynchronous programming and (that the Gods), garbage collection.

I confess that for me, this is the big attraction; not cross-platform development, but the ability to write for Android using the language and class library I know and love.  I first discovered C# in 2000, and have never gone back.  (Okay, that’s a lie, I’ve gone back to JavaScript, but not to C++, C or any of the other compiled languages I’ve used in the past).

Getting Set Up

Xamarin Download Page

There is often a lot of hand-waving in technical articles about what you have to do to set up your development environment, but with Xamarin it really is very easy.  Open a browser, navigate to Xamarin.com and click on Download Now.  Once downloaded, double click and everything you need is installed, including integration with Visual Studio 2012 (albeit, not with 2013 RC) and installation of Xamarin Studio.

Open Xamarin Studio and create a new project.

 From Java To Xamarin

It is Xamarin’s job to map the Java API to .NET and by and large it does a terrific job.  The .NET profile is smaller than all of .NET (as you’d expect, you certainly don’t need a lot of the desktop-specific stuff) and it includes a linker to remove all the cruft that you’re not using in your application.

You’ll be happy to know that the Mono runtime sits at the same architectural level as the Dalvik VM, which means you get hot-stuff performance.  Android wraps the Java classes, and it manages memory for you. In short, it does everything it can to turn Android into .NET – or at least a damn good imitation.

Creating Your First App

To get started, open the Xamarin studio and create a new solution.  Being a professional writer, I applied all my creativity and called my first application “MonoAndroidApp1”  – you are free to name yours whatever you like.

There are two folders for you to keep an eye on:

  • Assets – you keep fonts and other raw assets here

  • Resources – this gets divided into subfolders to hold just about anything that isn’t code.  Note that Xamarin uses the same resources as Android, so you can bring in Android resources as-is.

To get started, delete the files in Layout and Values and delete the .cs file that was created for you.  Then, right-click on the Layout folder and choose Add->New File (or NewItem if you are in Visual Studio).  Select Mono For Android -> Android Layout.  Name it First.axml.

We’re going to add a button to this first screen.  Its job is to call the second screen which will display the time we pressed the button.  You’ll find this program has limited utility, but it will get us going.

Here is the XAML you need to add to First.axml:

 

1. <?xml version="1.0" encoding="utf-8"?>
2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3.     android:orientation="vertical"
4.     android:layout_width="match_parent"
5.     android:layout_height="fill_parent">
6.     <Button
7.         android:id="@+id/Button"
8.         android:layout_width="match_parent"
9.         android:layout_height="wrap_content"
10.         android:text="Click Me!" />
11. </LinearLayout>

 

 

You can see that we’ve created a LinearLayout (exactly equivalent to a StackPanel) and within it a button.  Take the id naming convention on faith for now and note that you set the width and height to one of two values: match_parent or wrap_content.  The former will fill to the size of the container, the latter will not.

That should look good, so create a second view named, appropriately, Second.axml.  Here’s the code for Second.axml:

 

1. <?xml version="1.0" encoding="utf-8"?>
2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
3.     android:orientation="vertical"
4.     android:layout_width="fill_parent"
5.     android:layout_height="fill_parent">
6.     <TextView
7.         android:layout_width="match_parent"
8.         android:layout_height="wrap_content"
9.         android:paddingBottom="7dip"
10.         android:text="Button clicked at: " />
11.     <TextView
12.         android:id="@+id/Text"
13.         android:layout_width="match_parent"
14.         android:layout_height="wrap_content" />
15. </LinearLayout>

 

The first TextView serves as a label. The second displays the time. Since we’ll be addressing the second in code, it needs an id.  Notice that the label has a property “paddingBottom” set to 7dip. dip stands for Density Independent Pixels, and it is how you get reasonable consistency across Android devices.

Here is what the two screens look like when they run:

Click Me screen

Second Screen

What is nice is not the layout, but that they look like native Android screens.

Adding the Logic

Now that we have our UI, it is time to add the logic to go from one screen to the next.  You write your logic in Activities.  Activities are the heart and soul of Android.  They are single screens within the application, but they can be called and reused from anywhere; even other applications (!)

Android applications are defined by starting an activity based on the user’s goals, but irrespective of which application has the activity.  If more than one app has the activity the user gets to pick which app to use.

Activities are tied together with intents.  Intents are messages that tell Android what to do next. There are two types of intents: explicit and implicit.  Explicit intents essentially say “start this activity in this application” while implicit intents are less coupled to specific applications.  We’ll return to Activities and Intents a lot.  You can also read more about Activities here.

To add the logic for our first screen right click on the project, choose Add->New File and select Android->Activity.  Name the activity FirstActivity.cs.  Here are the contents (placed within your namespace):

 

1. [Activity (Label = "Hello Android!", MainLauncher=true, Icon="@drawable/icon")]           
2. public class FirstActivity : Activity
3. {
4.     protected override void OnCreate (Bundle bundle)
5.     {
6.         base.OnCreate (bundle);
7.
8.         SetContentView (Resource.Layout.First);
9.         var button = FindViewById<Button> (Resource.Id.Button);
10.         button.Click += buttonClicked;
11.     }
12.
13.     private void buttonClicked(object sender, EventArgs e)
14.     {
15.         var intent = new Intent(this, typeof(SecondActivity));
16.         intent.PutExtra ("text", DateTime.Now.ToLongTimeString ());
17.         StartActivity(intent);
18.     }
19. }

 

If you are a .NET programmer, it is an interesting mix of the familiar and the new.  We start with an Activity Attribute which lets the runtime know this is an Activity.  In that we also mark MainLauncher=-true indicating this is an entry point for the program.

The usual first entry point in the lifecycle of an Activity is OnCreate, which we call here on line 6.

SetContentView (line 8) sets the layout. Line 9 locates our button.  Line 10 sets the event handler for the button.

On line 15 we set a new intent based on the button click.  PutExtra on line 16 allows us to pass data into the intent.  With the intent ready we can pass it into StartActivity on line 17 which invokes the second page.

Here’s the code for page 2:

 

1. [Activity (Label = "Second Activity")]           
2. public class SecondActivity : Activity
3. {
4.     protected override void OnCreate (Bundle savedInstanceState)
5.     {
6.         base.OnCreate (savedInstanceState);
7.         SetContentView (Resource.Layout.Second);
8.         var text = FindViewById<TextView> (Resource.Id.Text);
9.         text.Text = Intent.GetStringExtra ("text");
10.     }
11. }

 

We find the second text box, and we populate it with the text passed in as Extra from page one (the time).

Running the Application

To run your new application click on Run -> Start Without Debugging (if you don’t need to be debugging, it runs much faster without it). Pick a device, load the device, wait a looong time for it to load the first time and voilà! you have an instant, if useless, Android application.

Full Disclosure

I’m learning Xamarin as I write these blog posts, so please be patient, it may take a while for each subsequent blog post to come out, and I’ll be correcting and filling in details as I go.  In the meantime, there are many excellent resources on the Xamarin web site, as well as on related sites.

Also, the example is loosely based on an example in the excellent book Mobile Development With C#.

Final Note

Today is September 11.  It is easy to forget, but we haven’t.

About the Author

Jesse Liberty is a Master Consultant for Falafel Software, an author and he creates courses for Pluralsight.    Liberty  hosts the popular Yet Another Podcast and his blog is required reading. He was a Senior Evangelist for Microsoft,  a XAML Evangelist for Telerik, a Microsoft MVP, Distinguished Software Engineer at AT&T; Software Architect for PBS and Vice President of Information Technology at Citibank. Jesse can be followed on twitter at @JesseLiberty

 

 

 

 

 

 

 

 

 

The following two tabs change content below.