Click here to Skip to main content
15,879,239 members
Articles / Mobile Apps / Android
Technical Blog

Developing Android Apps using C#

Rate me:
Please Sign up or sign in to vote.
4.89/5 (48 votes)
4 Oct 2013CPOL6 min read 373K   108   24
If you love C# and want to create an Android application using that language then you have to thank Xamarin as they created this great Cross Platform development tool which enables developers to develop iOS and Android apps in C# language. 

If you love C# and want to create an Android application using that language then you have to thank Xamarin as they created this great Cross Platform development tool which enables developers to develop iOS and Android apps in C# language. I tried developing before in Android but I did not like the experience in using the available IDE, as its slow and resource hungry, so I gave up. A couple of years after that I attended TechEd NZ 2013 and was introduced to this wonderful platform called Xamarin.

Xamarin is offered in different licenses from free to enterprise levels but for not I will be using the starter version which is the free version. It includes the Xamarin Studio which is great start for those who want to try out creating their first apps for Android, they also offer a Business license which lets you develop in Visual Studio so you can use that rich experience similar to developing Web Apps or Windows Apps, then they have this Enterprise which contains everything. For now lets see what the free stuff can offer, I did a simple project which I will be discussing below and it looks very promising, I love it.

Image 1

Like what I said above we will be using the free version so we will make this simple project by using Xamarin Studio. Now I was thinking what to do, I don’t want to create the boring "Hello World!" demo so what I will be developing is a simple calculator which acts like a normal desk calculator. Most of the calculator projects online regardless its C#, VB.Net developed as Windows
forms does not act like a normal desk calculator where you can continuously perform operations and deliver results through the screen, you can’t even change operations along the way, so I decided I will make this one and I accepted my own challenge.

Lets start! First you need to download Xamarin at https://store.xamarin.com/, while installing it will ask you to download as well prerequisites but is you are a developer most or all of them are already set up in your machine.

Once its downloaded you’re ready to roll!

Fire up Xamarin Studio and select new Solution then Android Application, give it a solution name and in this case we use "Calculator".

Image 2

Once all ok you will see the IDE which is like a cross between Visual Studio and Eclipse, it has intellisense and fancy text colours and highlighting.

Image 3

You will notice if you go to the Resources\layout they the UI is in a file called Main.axml which is a "Hello World" template.

Image 4

At this point we are more interested on the 2 files on the solution, that layout and the MainActivity.cs where we will be doing our coding.

Image 5

First lets design you calculator, you need to go to that Main.axml and start coding, you will notice its like Windows form where you can drag and drop items from the Toolbox on the right, it will also have its property window on the bottom left.

Image 6

Were not interested with the dragging and dropping part so let’s go the code behind (you can control it more), so hit that Source tab below the UI beside the content source. First thing you will notice is that it is in XML format, if you’re so used to drag and drop or HTML coding then you need a bit of learning here specially the layouts.

Common layouts used are Linear Layout, Relative Layout, List View and Grid View. To see how each of them would look like here is an illustration

Image 7

Linear Layout – you can organize objects in either horizontal or vertical rows.

Image 8

Relative Layout – specify the location of child objects relative to each other. For example object A is placed on the left of object B or it can be aligned to a parent.

Image 9

List View – Displays it in a scrolling single column list.

Image 10

Grid View – Displays it in a scrolling grid view of columns and rows.

Now lets start designing, for this project we will using a mix of Linear and Relative. Copy and Paste the code below then I will give you some explanation of what it does.

XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
  <EditText
      android:inputType="number"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:id="@+id/resultText" />
  <LinearLayout
android:id="@+id/wrapper0"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/resultText"
android:weightSum="1.0" >
    <Button
        android:text="Clear"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:id="@+id/buttonClear"
        android:layout_weight=".25" />
  </LinearLayout>
  <LinearLayout
android:id="@+id/wrapper1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/wrapper0"
android:weightSum="1.0" >
    <Button
        android:text="1"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight=".25"
        android:id="@+id/button1" />
    <Button
        android:text="2"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/button1"
        android:layout_alignTop="@+id/button1"
        android:layout_weight=".25"
        android:id="@+id/button2" />
    <Button
        android:text="3"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/button2"
        android:layout_alignTop="@+id/button2"
        android:layout_weight=".25"
        android:id="@+id/button3" />
    <Button
        android:text="+"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/button3"
        android:layout_alignTop="@+id/button3"
        android:layout_weight=".25"
        android:id="@+id/buttonAdd" />
  </LinearLayout>
  <LinearLayout
android:id="@+id/wrapper2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/wrapper1"
android:weightSum="1.0" >
    <Button
        android:text="4"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/wrapper2"
        android:layout_weight=".25"
        android:id="@+id/button4" />
    <Button
        android:text="5"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/button4"
        android:layout_alignTop="@+id/button4"
        android:layout_weight=".25"
        android:id="@+id/button5" />
    <Button
        android:text="6"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/button5"
        android:layout_alignTop="@+id/button5"
        android:layout_weight=".25"
        android:id="@+id/button6" />
    <Button
        android:text="-"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/button6"
        android:layout_alignTop="@+id/button6"
        android:layout_weight=".25"
        android:id="@+id/buttonSubtract" />
  </LinearLayout>
  <LinearLayout
android:id="@+id/wrapper3"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/wrapper2"
android:weightSum="1.0" >
    <Button
        android:text="7"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/wrapper3"
    android:layout_weight=".25"
        android:id="@+id/button7" />
    <Button
        android:text="8"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/button7"
        android:layout_alignTop="@+id/button7"
        android:layout_weight=".25"
        android:id="@+id/button8" />
    <Button
        android:text="9"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/button8"
        android:layout_alignTop="@+id/button8"
        android:layout_weight=".25"
        android:id="@+id/button9" />
    <Button
        android:text="x"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/button9"
        android:layout_alignTop="@+id/button9"
        android:layout_weight=".25"
        android:id="@+id/buttonMultiply" />
  </LinearLayout>
  <LinearLayout
android:id="@+id/wrapper4"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/wrapper3"
android:weightSum="1.0" >
    <Button
        android:text="(-)"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button7"
        android:layout_weight=".25"
        android:id="@+id/buttonNegative" />
    <Button
        android:text="0"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/buttonNegative"
        android:layout_alignTop="@+id/buttonNegative"
        android:layout_weight=".25"
        android:id="@+id/button0" />
    <Button
        android:text="."
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/button0"
        android:layout_alignTop="@+id/buttonNegative"
        android:layout_weight=".25"
        android:id="@+id/buttonDot" />
    <Button
        android:text="/"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/buttonDot"
        android:layout_alignTop="@+id/buttonDot"
        android:layout_weight=".25"
        android:id="@+id/buttonDivide" />
  </LinearLayout>
  <Button
      android:text="="
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_below="@+id/wrapper4"
      android:id="@+id/buttonEquals" />
</RelativeLayout>

Most of the objects are created similar to an HTML tags like and <EditText>. Also like HTML Tags they will have properties and the common ones we used are:

  • orientation – this sets our object orientation either vertical or horizontal.
  • layout_width – fill_parent will fill depending on the parent with, you can also specify a with by using something like 200dp. If you want to use percentage use 0dp but we will be indicating percentage on layout_weight.
  • layout_height – similar to layout_width.
  • layout_weight – this indicated the percentage you will use on the width.
  • id – identifier to the object.
  • layout_toRightOf – this indicates you will place this object to the right of what object Id.
  • layout_alignTop – this aligns your object similar to what object Id.
  • layout_below – this will place your object below the object Id.

other elements would sound similar to .Net object properties. Now click your content tab to see how it looks. It should be something like this

Image 11

Now you have your UI, you need to start coding in C#, so go to your MainActivity.cs

To display the layout you need to do this.

SetContentView (Resource.Layout.Main);

Then you will notice that objects are not natively available in code, you cant do something like this

resultText.Text = "";

you need to find it like how you find objects but ID in a grid during the ASP.Net days. To do it here is a sample for button1

Button button1 = FindViewById<Button> (Resource.Id.button1);

Now you have your button1, you can assign a delegate and define what it should do when you click

button1.Click += delegate {

//Your stuff here

};   

Other than that you’re good to go, everything should be easy. So for the full code just copy and paste the one below, it’s an operational calculator.

XML
using System;
using Android.App;
using Android.Content;
using Android.Runtime;
using Android.Views;
using Android.Widget;
using Android.OS;

namespace SampleAndroidApp
{
    [Activity(Label = "Ray's Calculator", MainLauncher = true)]
    public class MainActivity : Activity
    {
        private enum Operation { Addition, Subtraction, Division, Multiplication };
        private enum LastKeyInput { Digit, Operator, Equal, DecimalPoint, Sign }

        decimal? digitMemory = null;
        decimal? totalMemory = null;

        Operation? operationMemory = null;

        LastKeyInput? lastKeyInput = LastKeyInput.Digit;

        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Get our button from the layout resource,
            // and attach an event to it
            Button button1 = FindViewById(Resource.Id.button1);
            Button button2 = FindViewById(Resource.Id.button2);
            Button button3 = FindViewById(Resource.Id.button3);
            Button button4 = FindViewById(Resource.Id.button4);
            Button button5 = FindViewById(Resource.Id.button5);
            Button button6 = FindViewById(Resource.Id.button6);
            Button button7 = FindViewById(Resource.Id.button7);
            Button button8 = FindViewById(Resource.Id.button8);
            Button button9 = FindViewById(Resource.Id.button9);
            Button button0 = FindViewById(Resource.Id.button0);
            Button buttonDot = FindViewById(Resource.Id.buttonDot);
            Button buttonNegative = FindViewById(Resource.Id.buttonNegative);

            EditText resultText = FindViewById(Resource.Id.resultText);

            Button buttonAdd = FindViewById(Resource.Id.buttonAdd);
            Button buttonSubtract = FindViewById(Resource.Id.buttonSubtract);
            Button buttonMultiply = FindViewById(Resource.Id.buttonMultiply);
            Button buttonDivide = FindViewById(Resource.Id.buttonDivide);
            Button buttonEquals = FindViewById(Resource.Id.buttonEquals);
            Button buttonClear = FindViewById(Resource.Id.buttonClear);

            buttonNegative.Click += delegate
            {
                //handles if negative sign is the first input after calculation
                if (lastKeyInput != LastKeyInput.Digit && lastKeyInput != LastKeyInput.DecimalPoint && lastKeyInput != LastKeyInput.Sign)
                {
                    resultText.Text = "-";
                    lastKeyInput = LastKeyInput.Sign;
                    return;
                }
                //handles multiple negative sign
                if (!resultText.Text.Contains("-"))
                {
                    resultText.Text = "-" + digitMemory.ToString();
                    lastKeyInput = LastKeyInput.Sign;
                }

            };
            buttonDot.Click += delegate
            {
                //handles if decimal point is the first input after calculation
                if (lastKeyInput != LastKeyInput.Digit && lastKeyInput != LastKeyInput.DecimalPoint && lastKeyInput != LastKeyInput.Sign)
                {
                    resultText.Text = ".";
                    lastKeyInput = LastKeyInput.DecimalPoint;
                    return;
                }
                //handles multiple decimal point
                if (!resultText.Text.Contains("."))
                {
                    resultText.Text = digitMemory.ToString() + ".";
                    lastKeyInput = LastKeyInput.DecimalPoint;
                }

            };
            button1.Click += delegate
            {
                //Renders Text on Screen
                RenderCurrentValue(resultText.Text, "1");
                resultText.Text = digitMemory.ToString();

                //Perform calculation based on current operator
                Calculate();
                lastKeyInput = LastKeyInput.Digit;
            };

            button2.Click += delegate
            {
                RenderCurrentValue(resultText.Text, "2");
                resultText.Text = digitMemory.ToString();
                Calculate();
                lastKeyInput = LastKeyInput.Digit;
            };

            button3.Click += delegate
            {
                RenderCurrentValue(resultText.Text, "3");
                resultText.Text = digitMemory.ToString();
                Calculate();
                lastKeyInput = LastKeyInput.Digit;
            };

            button4.Click += delegate
            {
                RenderCurrentValue(resultText.Text, "4");
                resultText.Text = digitMemory.ToString();
                Calculate();
                lastKeyInput = LastKeyInput.Digit;
            };

            button5.Click += delegate
            {
                RenderCurrentValue(resultText.Text, "5");
                resultText.Text = digitMemory.ToString();
                Calculate();
                lastKeyInput = LastKeyInput.Digit;
            };

            button6.Click += delegate
            {
                RenderCurrentValue(resultText.Text, "6");
                resultText.Text = digitMemory.ToString();
                Calculate();
                lastKeyInput = LastKeyInput.Digit;
            };

            button7.Click += delegate
            {
                RenderCurrentValue(resultText.Text, "7");
                resultText.Text = digitMemory.ToString();
                Calculate();
                lastKeyInput = LastKeyInput.Digit;
            };

            button8.Click += delegate
            {
                RenderCurrentValue(resultText.Text, "8");
                resultText.Text = digitMemory.ToString();
                Calculate();
                lastKeyInput = LastKeyInput.Digit;
            };

            button9.Click += delegate
            {
                RenderCurrentValue(resultText.Text, "9");
                resultText.Text = digitMemory.ToString();
                Calculate();
                lastKeyInput = LastKeyInput.Digit;
            };

            button0.Click += delegate
            {
                RenderCurrentValue(resultText.Text, "0");
                resultText.Text = digitMemory.ToString();
                Calculate();
                lastKeyInput = LastKeyInput.Digit;
            };

            buttonClear.Click += delegate
            {
                resultText.Text = "";
                ResetMemory();
            };

            buttonAdd.Click += delegate
            {
                if (lastKeyInput == LastKeyInput.Digit || lastKeyInput == LastKeyInput.Operator)
                {
                    operationMemory = Operation.Addition;
                }
                resultText.Text = totalMemory.ToString();
                lastKeyInput = LastKeyInput.Operator;
            };

            buttonSubtract.Click += delegate
            {
                if (lastKeyInput == LastKeyInput.Digit || lastKeyInput == LastKeyInput.Operator)
                {
                    operationMemory = Operation.Subtraction;
                }
                resultText.Text = totalMemory.ToString();
                lastKeyInput = LastKeyInput.Operator;
            };

            buttonMultiply.Click += delegate
            {
                if (lastKeyInput == LastKeyInput.Digit || lastKeyInput == LastKeyInput.Operator)
                {
                    operationMemory = Operation.Multiplication;
                }
                resultText.Text = totalMemory.ToString();
                lastKeyInput = LastKeyInput.Operator;
            };

            buttonDivide.Click += delegate
            {
                if (lastKeyInput == LastKeyInput.Digit || lastKeyInput == LastKeyInput.Operator)
                {
                    operationMemory = Operation.Division;
                }
                resultText.Text = totalMemory.ToString();
                lastKeyInput = LastKeyInput.Operator;
            };

            buttonEquals.Click += delegate
            {
                lastKeyInput = LastKeyInput.Equal;
                resultText.Text = totalMemory.ToString();
                ResetMemory();
            };

        }

        private void Calculate()
        {
            if (operationMemory != null)
            {
                switch (operationMemory)
                {
                    case Operation.Addition:
                        if (totalMemory == null)
                        {
                            //Handles first entry
                            totalMemory = digitMemory;
                        }
                        else
                        {
                            totalMemory = totalMemory + digitMemory;
                        }
                        lastKeyInput = LastKeyInput.Operator;
                        break;

                    case Operation.Subtraction:
                        if (totalMemory == null)
                        {
                            //Handles first entry
                            totalMemory = digitMemory;
                        }
                        else
                        {
                            totalMemory = totalMemory - digitMemory;
                        }
                        lastKeyInput = LastKeyInput.Operator;
                        break;

                    case Operation.Multiplication:
                        if (totalMemory == null)
                        {
                            //Handles first entry
                            totalMemory = digitMemory;
                        }
                        else
                        {
                            totalMemory = totalMemory * digitMemory;
                        }
                        lastKeyInput = LastKeyInput.Operator;
                        break;

                    case Operation.Division:
                        if (totalMemory == null)
                        {
                            //Handles first entry
                            totalMemory = digitMemory;
                        }
                        else
                        {
                            totalMemory = totalMemory / digitMemory;
                        }
                        lastKeyInput = LastKeyInput.Operator;
                        break;
                }
            }
            else
            {

                totalMemory = digitMemory;

            }
        }

        private void RenderCurrentValue(string currentRenderedValue, string character)
        {
            //display multiple digits
            if (lastKeyInput == LastKeyInput.Digit || lastKeyInput == LastKeyInput.DecimalPoint || lastKeyInput == LastKeyInput.Sign)
            {
                digitMemory = decimal.Parse(currentRenderedValue + character);
            }
            else
            {
                digitMemory = decimal.Parse(character);
            }
        }

        private void ResetMemory()
        {
            totalMemory = null;
            digitMemory = null;
            operationMemory = null;
            lastKeyInput = LastKeyInput.Digit;
        }
    }

}

Just a side note : You might notice Calculate happens on each digit press, this makes sure you have a running total even before you hit the operator. The operator buttons will just store the current operator needed for your next digit press.

Other than that you are now all good to go, just hit run

Image 12

It will now ask you for a device, if you don’t have an emulator yet then you can create one, choose create emulator then hit OK.

Image 13

Click New

Image 14

Then I suggest create something similar to a device you have, so you can play around with it on your device.

Image 15

Once created hit start, then launch

Image 16

You will now see it will start, and it will also show you any errors it encounter.

Image 17

Once started go back to Xamarin and choose the device you want your app to run on, in this case your newly created emulator, it will then be automatically deployed on the emulator.

Image 18

You will then see the progress on the middle top part of the IDE.

Image 19

Then on your emulator

Image 20

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Technical Lead
New Zealand New Zealand
http://nz.linkedin.com/in/macaalay
http://macaalay.com/

Comments and Discussions

 
Questionwant to convert the c# web-based project into mobile-based(xamarin) Pin
Member 134855138-Nov-17 23:28
Member 134855138-Nov-17 23:28 
QuestionGetting Blank Screen Pin
Member 1326986020-Jun-17 8:05
Member 1326986020-Jun-17 8:05 
Questionproblem with convert type Pin
Kishor Tiwari16-Aug-15 18:04
Kishor Tiwari16-Aug-15 18:04 
Question[My vote of 1] The name Resource does not exist in current context. Pin
Member 118185706-Jul-15 21:29
Member 118185706-Jul-15 21:29 
AnswerRe: [My vote of 1] The name Resource does not exist in current context. Pin
Member 1185084420-Jul-15 19:05
Member 1185084420-Jul-15 19:05 
GeneralRe: [My vote of 1] The name Resource does not exist in current context. Pin
Kishor Tiwari16-Aug-15 17:53
Kishor Tiwari16-Aug-15 17:53 
GeneralMy vote of 1 Pin
Member 118185706-Jul-15 21:27
Member 118185706-Jul-15 21:27 
GeneralMy vote of 1 Pin
Krupal516-Nov-14 23:55
Krupal516-Nov-14 23:55 
QuestionError...pls help Pin
Member 1103644625-Aug-14 21:29
Member 1103644625-Aug-14 21:29 
AnswerRe: Error...pls help Pin
Jay Thompson26-Sep-14 10:37
Jay Thompson26-Sep-14 10:37 
AnswerRe: Error...pls help Pin
Member 1185084420-Jul-15 19:07
Member 1185084420-Jul-15 19:07 
GeneralMy vote of 2 Pin
Pankaj Nema12-Jun-14 21:02
Pankaj Nema12-Jun-14 21:02 
GeneralMy vote of 3 Pin
ggeorgiev898-Jun-14 23:35
professionalggeorgiev898-Jun-14 23:35 
QuestionCode Doesn't show anything in Emulator Pin
Pavan52828-May-14 16:34
Pavan52828-May-14 16:34 
QuestionGreate article. Pin
amit_831-Apr-14 19:20
professionalamit_831-Apr-14 19:20 
QuestionAndroid Apps using c# Pin
Ehtesham Mehmood21-Feb-14 11:18
professionalEhtesham Mehmood21-Feb-14 11:18 
QuestionDivide by zero bug Pin
Max Vagner29-Jan-14 1:29
Max Vagner29-Jan-14 1:29 
GeneralMy vote of 5 Pin
Gun Gun Febrianza10-Nov-13 19:33
Gun Gun Febrianza10-Nov-13 19:33 
Question"Application does not have a launchable activity" Pin
ppayal7-Nov-13 3:13
ppayal7-Nov-13 3:13 
AnswerRe: "Application does not have a launchable activity" Pin
anujk02926-Mar-14 22:30
anujk02926-Mar-14 22:30 
Questionapp not shown in emulator Pin
heemanshubhalla11-Oct-13 9:18
heemanshubhalla11-Oct-13 9:18 
QuestionA few things are not right here PinPopular
FZelle10-Oct-13 5:55
FZelle10-Oct-13 5:55 
AnswerRe: A few things are not right here Pin
AnonJ19-Nov-13 2:36
AnonJ19-Nov-13 2:36 
QuestionRe: A few things are not right here Pin
DavidMills0219-Oct-14 4:23
DavidMills0219-Oct-14 4:23 

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.