Tag Archives: phone

Controlling an LED light using a mobile app and Bluetooth

This tutorial will show you how to control an LED light on an Arduino using a mobile app and a Bluetooth wireless connection.

Parts required

Here is what you’ll need:

  • An Android phone or iPhone
  • A free mobile app
  • Arduino Uno board
  • Breadboard
  • 220 Ohm resistor
  • 6 male-to-male jumper wires
  • HM-10 BLE Bluetooth 4.0 module (see bottom of page for exact model used in this tutorial)
  • An LED light
  • Arduino IDE software

Wiring it up

Wire up the project using jumper wires by following these instructions or checking out the circuit diagram and images below.

  1. Connect VCC on Bluetooth module to 3.3V on Arduino
  2. Connect GND on Bluetooth module to GND on Arduino
  3. Connect TXD on Bluetooth module to digital pin 7 on Arduino
  4. Connect RXD on Bluetooth module to digital pin 8 on Arduino
  5. Connect the long pin from the LED on the breadboard to digital pin 2 on Arduino
  6. Connect the short pin from the LED on the breadboard to a 220 Ohm resistor and from there to GND on the Arduino

Note: The STATE and EN pins on the Bluetooth module do not need to be connected to anything in this project.

Bluetooth

Here are some images showing the LED turned on and everything wired up.

IMG_1905

IMG_6092

IMG_5111

Arduino code

Create a new sketch in the Arduino IDE and add the following code. Then upload the sketch to your Arduino board.

#include <SoftwareSerial.h>
int led = 2;

SoftwareSerial Bluetooth(7, 8);

void setup() {  
  Serial.begin(9600);
  Bluetooth.begin(9600);
  pinMode(led, OUTPUT);
}

void loop() {  
  int command;
  
  if (Bluetooth.available()) {
    command = Bluetooth.read();  
    Serial.println("Input received:");
    if (command != 0)
    {
      // A non-zero input will turn on the LED
      Serial.println("0 / ON");
      digitalWrite(led, HIGH);
    }
    else
    {
      // A zero value input will turn off the LED
      Serial.println("1 / OFF");
      digitalWrite(led, LOW);
    }  
  }
}

Controlling the Arduino via Bluetooth

To connect your Android or iOS mobile device to the Arduino you will need to download a free app (or you could also make your own app) that can connect to the HM-10 Bluetooth module and send commands. You can search your device’s app store to find a free app that will work for this project but for this example we will use the free Bluetooth Terminal app on iOS.

Tip: If you search the iOS App Store or Google Play app store using the keywords “bluetooth arduino” or “bluetooth hm-10” you should be able to find a suitable app.

The steps below are for the Bluetooth Terminal app on iOS but will be similar for other apps on other devices:

  1. Open the app and connect to the Bluetooth module (in this case it is called CC41-A but the name will vary depending on the model you have).
    IMG_4901
  2. Tap ‘Select characteristic’ and then select FFE1 (at the bottom of the list).
    IMG_4902
  3. Select Decimal.
  4. Using the on-screen keypad, you can enter different decimal values. Enter 1 and tap the Send button. The LED light should turn on. Enter 0 and tap the Send button. The LED should then turn off. If you don’t see anything happen, click Tools > Serial Monitor in the Arduino IDE and then set the baud date to 9600 bauds. Check if any input is being received and displayed in the serial monitor when you send the 0 or 1 commands to the Arduino from the app.
    IMG_4903

Where to from here?

You can use Bluetooth to control other projects such as a robot or car. You can also try receiving data from the Arduino – eg. send sensor readings to your phone.

Which Bluetooth module should I use?

There are several different Bluetooth modules that should work with this tutorial. The one used in this project was purchased on eBay and is called “HM-10 CC2540 CC2541 BLE Bluetooth 4.0 Wireless Module“.

Creating a custom list in Android with Xamarin

This tutorial will show you how to create a detailed list for an Android app using your own custom list design. For this project, we will create a list of cities and when the user taps a city from the list, the app will take them to another screen with more details about that city.

customlistandroid

Step 1

Click File > New Solution and select Android App. Click Next.

image3

Then give the app a name, select a target version of Android and click Next.

image4

Step 2

Confirm the project name, solution name, location and click Create.

image5

Step 3

Open the MainActivity.cs file and change MainActivity : Activity to say MainActivity : ListActivity . You can also delete the existing code for the default button. The code should look like this:

image6
Click image to see larger version.

Step 4

You can also go ahead and delete the following two lines of code from the MainActivity.cs file as it will not be needed (because we will not be loading the Main screen, we will be loading a list):

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

Next, add using System.Collections.Generic; so we can use a list, and then create the City class which will define the properties for a city.

image7
Click image to see larger version.

You can also now add the following two lines of code to create a list called cityList.

image8
Click image to see larger version.

Step 5

Now you can start populating your cities list with some cities and their information. Add as many as you like. Two cities have been added below with the properties Name, Country, State, and Population.

image9
Click image to see larger version.

Step 6 

You will now need to create an adapter which is an ArrayAdapter as we are going to be working with an array for a list.

image10
Click image to see larger version.

Step 7

Inside the City class, add a public override string ToString() method. Inside the new method, add the code shown below so that you can display the city information in each row of the list. The way it is formatted works like this: The numbers (0,1,2,3) represent each of the elements displayed in a row. For example, in the code below {0} s matched to the city Name, {1} is matched to the state, {2} is matched to the country name, and so on. Inside the double-quotes, you can specify each element and how they will be formatted (eg. separated by commas or dashes).

image11
Click image to see larger version.

The code above will result in a list that looks like this when you test the app:

image12

Clearly, the formatting needs improving but we can work with this for now to have a rough idea of what the list will look like. We can now focus on making a custom row for the list.

Step 8

Right-click the layout folder inside the Resources folder and then click Add > New File.

image13

Then select Android > Layout. Give the new layout the name CityCell and click New.

image14

Step 9

Open the new CityCell.axml file and drag three LinearLayout (Horizontal) elements on to the screen.

image15

Now drag a Text (Large) element on to the first LinearLayout (this will be for the city name), two Text (Medium) elements next to each other on the second LinearLayout (for state and country), and then a Text (Small) element on the third (bottom) LinearLayout (this will be for the population). Change their default Text value so that you know what each text element is for (eg. City name, State, Country, Population).

Give them the following Id values:

  • @+id/cityNameTextView
  • @+id/stateTextView
  • @+id/countryTextView
  • @+id/populationTextView

image16

You can also add some padding to the left side of each text view element by clicking on the Layout tab on the Properties panel and adding a dp value for Left padding eg. 10dp – now is a good time to save the file.

image17

Step 10

Now that we have defined our own custom layout, we can go back and change the adapter in the MainActivity.cs file. Instead of using SimpleListItem1, we can use our own new custom layout for the list items / rows. To do this, right-click the project folder, click Add > New file.

image18

In the New File dialog, select General > Empty Class and then give it the name CitiesAdapter and click New.

image19

In the CitiesAdapter.cs file, add the following highlighted lines of code to create a new list and a new activity.

image20

Step 11

Now modify the code as you see it below. Don’t worry if you are getting error messages at this point – we will fix those in the next steps. Firstly, the CitiesAdapter will need to inherit from BaseAdapter, so we specify this (line 8). For this, we also require using Android.Widget; (line 4). We also need to create and define an activity in this file. In the constructor of the CitiesAdapter method we will be receiving an activity (line 13), and we will set the value of the local activity to the one we get from the argument (line16). We will also create the cities list here (line 15).

image21

Add a new public override Count method by typing in public override count and then double-click Count from the list or press Enter to select it.

image22

Change the Count override method so that it will return cities.Count;

image23

Step 12

We need to add another override method. We need to add the public override GetView method by typing in public override GetView and then double-clicking or pressing Enter to select the GetView method.

image24
Click image to see larger version.

The following highlighted method below will be added to your code.

image25
Click image to see larger version.

Now we need to create a view and we do this by modifying the method we just created. Replace the line of code inside the method (shown on line 30 above) with the following line:

var view = convertView ?? activity.LayoutInflater.Inflate(ListAppAndroid.Resource.Layout.CityCell, parent, false);

The method will now look like this:

image26
Click image to see larger version.

Step 13

Now we can start adding the different text label elements for this view.

image27
Click image to see larger version.

Step 14

Now we need to get the data which will be equal to cities in the position that we will get from the arguments. The label text will contain this data. Then we can return the view.

image28
Click image to see larger version.

Step 15

Next, we create a new method. Start typing public override GetItem and then select the GetItem method from the list to create it.

image29
Click image to see larger version.

Step 16

Change the line of code inside the new GetItem method to return null; because we don’t need to return anything at the moment.

image30
Click image to see larger version.

Step 17

We will now need to create a new id that may be requested. Go back to the MainActivity.cs file and located the public class City. Add public long Id; to your class. Save the file.

image31
Click image to see larger version.

Step 18

Return to the CitiesAdapter.cs file. Another method needs to be created. Start typing public override GetItemId and then select the GetItemId method from the autocomplete list to create it.

image32
Click image to see larger version.

We now need to get the city in the position that’s been requested so we need to change the code inside the new GetItemId method to return cities[position].Id; – save the file.

image33
Click image to see larger version.

Now that we have the CitiesAdpater we can start using it instead of ArrayAdapter. Go back to MainActivity.cs and change the ListAdapter as shown below (make sure you pay attention to where you use uppercase letters and where you don’t use them). Save the file.

image34
Click image to see larger version.

Step 19

One last thing you can do to touch up the appearance of the list is to change the way the population number on the label is formatted so that hundreds and thousands are separated by commas.

Go to the GetView method in CitiesAdapter.cs. Then find the line populationLabel.Text = … and add “#,##0” inside the ToString brackets – this will format numbers with comma in between hundreds and thousands.

image35
Click image to see larger version.

That’s it! Now if you test the app, it should look something like this:

image1

The second part of this tutorial focuses on adding a details screen so that when the user taps one of the cities on the list, they can find out more information about it.

Step 20

Start by adding a new screen. Right-click the layout folder, click Add > New File.

image36

Step 21 

Call the new layout file Details and then open this new Details.axml file.

image37

Step 22

Add a Text (Large) element and an ImageView element to the new Details screen. Then change the Id for the text element to @+Id/cityNameTextView2 (remember, that we already have a cityNameTextView). Also, change the ImageView element’s Id to @+id/cityImageView. You can also resize the image and add padding to the left side of the text.

image38

Step 23

Now you will need to create a DetailsActivity.cs file. To do this, right-click the project folder, click Add > New File and call it DetailsActivity.

image39

image40

Step 24

Add some images to your drawable folder inside the Resources folder. Right-click the drawable folder and click Add > New File.

image41

Find the folder that contains the images you want to use. Click Open.

image42

Select the images you wish to use and click OK.

image43

Select Copy the file to the directory and click OK.

image44

Step 25

Open the MainActivity.cs file. Add public int ImageId; to the public class City.

image45
Click image to see larger version.

Then scroll up to the OnCreate method and specify the ImageId for each item in the list.

image46

Step 26

Add an ItemClick event for the ListView which will create a new method called ListView_ItemClick.

image47
Click image to see larger version.

Step 27

Inside the ListView_ItemClick method, firstly we will check that the event argument is not empty. Then we will create an intent, send the city name and image ID with the intent, and start the new activity (the Details screen).

image48
Click image to see larger version.

Step 28

Now go back to the DetailsActivity.cs file created earlier and add the following highlighted code. This will create the TextView and ImageView, get the selected city and its data, then display the data (the city name and image) on the screen.

image49
Click image to see larger version.

And that’s it! Now you can test your app by tapping on one of the items on the list to see its details.

image2

 

Using Toasts to display messages in Android

A Toast is a small message that is temporarily displayed at the bottom of a screen in Android apps and is usually used to notify the user that something has occurred or changed, or to confirm an action that the user took such as saving a file or sending a message. The example app below shows a Toast that gives a confirmation to the user that they clicked a button. The Toast will appear when the button is clicked and then disappear a few seconds later.

image1

Step 1

For this example, we will display a Toast when a button is clicked. Add a button to your app’s screen. In this example, we are using the Main.axml screen and the default button.

image2

Step 2

When the button is clicked it will display a toast. You need to define the button in your code and create a click event for it. You can use the existing button and click event that usually exists by default when you create a new Android app, if you wish.

The following line needs to be added inside the click event for the button to make the Toast appear:

Toast.MakeText(this, "You clicked the button", ToastLength.Long).Show();

The complete code should look something like this:

image3
Click the image to see a larger version.

The string message inside the quotes could also be replaced with a variable’s value, or you could also display a variable’s value joined to a string. The Toast can be used for any event such as a click event, when an option is selected or changed, after a certain time period, when something is received, or even just when the app loads.

Go and test your app and it should look something like this when the Toast appears after clicking the button.

image1

Adding toggle buttons to an Android app with Xamarin

This tutorial will show you how to add and use ToggleButton elements for Android apps in Xamarin. ToggleButtons are like on/off switches that only have two possible states and can only be in one state at any one time.

Toggle buttons in an app look like this:

image5

Step 1

To get started, create an Android app solution in Xamarin and open the Main.axml file from the Resources > layout folder. Drag a ToggleButton element on to the screen from the toolbox and give it an Id (eg. @+id/toggleButton1).

image1

The default text for a ToggleButton that is on is “ON” and the default text for a ToggleButton that is off is “OFF”. However, you can change this from the Properties panel.

image2

Step 2

Add a Text (Medium) element to the screen that will display a change in result (eg. ToggleButton switching from off to on). This example TextView is named @+id/resultTextView1.

image3

Step 3

Save the Main.axml file and go to the MainActivity.cs file. Define and set up the ToggleButton and TextView elements in the code and add a CheckedChange method which checks when a change in state is detected. The if statement will check if the ToggleBox is checked and will display the result.

image4
Click the image to see a larger version.

Now go and test your app and this is what it should look like…

image5

Adding radio buttons to an Android app with Xamarin

This tutorial explains how to add radio buttons to an Android app and make decisions based on which option the user selects. Radio buttons allow the user to select one item from a list of items. This is what an app screen with radio buttons looks like:

image10

Step 1

To get started, create a new Android app solution in Xamarin and then open the Main.axml file (in the Resources > layout folder). Drag a Text (Medium) element and three RadioButton elements from the Toolbox on to the app screen. Change the Text values on each element from the Properties panel and make sure each radio button has a name (eg. radioButton1, radioButton2, radioButton3) after @+id/ in the Id field on the Properties panel.

image1

Step 2

Add a Space element and another Text (Medium) element to your screen. Resize the Space element to make some space between the radio buttons and the Text (Medium) element. Give the Text (Medium) element a name eg @+id/resultTextView.

image2

Step 3

Open the MainActivity.cs file and define the three radio buttons and the text view. Then add them to the OnCreate method, so they can be accessed by the code.

image3

Step 4 

Now add a click event for each radio button so that the app displays a message saying which option was selected.

image4

Save your code and test the app. The example shown below is what you should see. However, the problem is that once you select an option it can’t be de-selected. Also, when using radio buttons you should only be able to select one option at a time but at the moment you can have more than one option selected at a time. We will fix this in the next section.

image5

Step 5

Go back to the screen design and delete all three radio buttons. Replace these radio buttons with a RadioGroup from the toolbox. This RadioGroup element has the name @+id/radioGroup1 . You will notice that the RadioGroup provides you already with three radio buttons grouped together. A RadioGroup can have any amount of radio buttons in it, but only one can be selected at a time.

image6

If you go to the Source view you can see that you can add more RadioButton elements to belong to the RadioGroup as long as you add them inside the RadioGroup tags.

image7

Change the Text value on each RadioButton so they are different.

image8

Step 6

Save the Main.axml file and go back to the MainActivity.cs file. The code needs to be changed so now it can access the RadioGroup element. A CheckChanged event is also added to detect when an option has been checked by the user. When this event fires, the option they selected is store in the option variable and the result is displayed to the user.

image9

Now if you test your app, it should look like what you see below. You could now add if statements to check which radio button was selected and have another event occur.

image10

Play audio in an iOS app with Xamarin

This tutorial explains how to play audio files in the background in an iOS app. An audio file can play when a screen loads or when an event occurs (such as a button press or change in a variable’s value). The example app in this tutorial will play a sound when a button is pressed. We will also look at how to use the Vibrate function in an iPhone to make the phone vibrate as well as playing a sound.

Here is what this app will look like:

ia_app

Step 1 

Open Xamarin and click File > New Solution. Then select iOS App and SingleView App as the project template. Click Next.

ia1

Step 2

Give your new app a name and select a target iOS version. Click Next. On the following screen, confirm the project and solution name and then click Create.

ia2

Step 3

When the solution opens, right-click on the project folder. Select Add > New Folder.

ia3

Give the new folder the name Sounds.

ia3b

Step 4

Right-click on the new Sounds folder and select Add > Add files from folder.

ia4

Step 5

Navigate to the folder which contains the audio file(s) you wish to use in your app. Click Open.

ia4b

Step 6 

Select the audio files you wish to include in the project (for this example, we will use an MP3 file called mysound.mp3). Click OK.

ia5

Then select Copy the file to the directory and click OK. This file will be copied to the project’s Sounds folder. You should then be able to see the audio file in the Sounds folder within the project folder from the Solution panel.

ia5b

Step 7

Right-click on the audio file in the Sounds folder. Select Build Action and set to BundleResource (if this does not work during testing, try selecting Content instead).

ia6

Step 8

Open the Main.storyboard file. Change the View to your desired iPhone/iPad model. Drag three Button elements on to the screen as shown below. Give the first button a Name of playSoundButton and the text value ‘Play sound’. Give the second button a Name of playSoundVibrateButton and the text value ‘Play sound and vibrate’. Give the third button a Name of vibrateButton and the text value ‘Vibrate’. Save the file.

ia7
Click the image to see a larger version.

Step 9

Open the ViewController.cs file and add the following two highlighted lines of code. The first two highlighted lines allow us to access audio tools and lower-level classes. url defines where the location and name of the audio file, while mySound is the name of the variable holding the sound file.

ia8
Click the image to see a larger version.

Step 10

Now add the following two highlighted lines of code in the ViewDidLoad method. Here we define the location and filename of the audio file as well as directing the mySound variable to use this audio file. Replace mysound.mp3 with the name of your sound file.

ia9
Click the image to see a larger version.

Step 11 

Now create a TouchUpInside event for each of the three buttons in the ViewDidLoad method. Inside the new methods for each TouchUpInside event, add the lines of code shown below.

  • SystemSound.PlaySystemSound(); will just play the sound
  • SystemSound.PlayAlertSound(); will play the sound and vibrate the phone
  • SystemSound.Vibrate.PlaySystemSound(); will just vibrate the phone
ia10
Click the image to see a larger version.

That’s it! Now go and test the app!

Play audio in an Android app with Xamarin

This tutorial explains how to play audio in an Android app made in Xamarin. The audio can be played when a screen loads or when an event occurs such as a button click or change in a variable’s value. For this tutorial, we will play a sound when a button is tapped.

au_app

Step 1

Start by creating a new app solution in Xamarin (click File > New Solution). Select Android App as the project template. Click Next.

au1

Give the new app a name. Then click Next.

au2

Confirm the solution and project name, Make sure you specify a folder to store your project files in and then click Create.

au3

Step 2

Open the Main.axml file (in Resources > layout). Delete the button already there. Save the file.

au4

Step 3 

Open the MainActivity.cs file and delete the highlighted lines of code (these lines for the button are not needed anymore as we won’t be using the default button).

au5

Step 4 

Right-click on the Resources folder. Select Add > New Folder.

au6

Give the new folder the name ‘raw’ and then press Enter.

au6b

Step 5

Select the new ‘raw’ folder and right-click it. Then click Add > Add files from folder.

au7

Step 6

Navigate to the folder which contains the audio file(s) you wish to use in your app. Click Open.

au7b

Step 7

Select the audio files you wish to include in the project (for this example, we will use an MP3 file called mysound.mp3). Click OK.

au8

Then select Copy the file to the directory and click OK. This file will be copied to the project’s raw folder. You should then be able to see the audio file in the raw folder from the Solution panel.

au8b

Step 8

Open the Main.axml file again and drag a Button element from the Toolbox onto the phone screen. Change the button’s Id value to @+id/playButton. Then change its Text value to Play Sound. Save this file.

au9

Step 9

Open the MainActivity.cs file again. Add the following highlighted line of code to the top section of the existing code. This will give us access to Android.Media.

au10
Click the image to see a larger version.

Step 10

Add the following two highlighted lines of code to the MainActivity.cs file to define the MediaPlayer element and to include the audio file in the code. Replace mysound with the name of your audio file (there is no need to include the .mp3 extension).

au11
Click the image to see a larger version.

Step 11

Now add the following two highlighted lines of code to define the Button element and access the playButton button from the screen.

au12
Click the image to see a larger version.

Step 12

Now add a click event for the button inside the OnCreate method. As you type playButton.Click+= and press the spacebar key you will see a list of options. You should see the option to create the PlayButton_Click method (if you don’t, start typing its name until it shows up – as shown below). Double-click this option from the list to create a new method.

au13
Click the image to see a larger version.

Step 13

Inside the new PlayButton_Click method add the line _player.Start(); – this will play the sound file when the button is clicked/tapped by the user. You can use this line anywhere in your app to play the sound (not just on a click event).

au14
Click the image to see a larger version.

That’s it! Now go and test your app. Hint: You can also add a button that runs the line of code _player.Stop(); to stop the audio file playing.

au15

Passing data between screens on Android with Xamarin

In this tutorial you will learn how to create an Android app that can pass data from one screen to another. This will be demonstrated in an example app that will ask the user for their age and will then convert their age to into animal years (of different types of animals). The user will select an animal by tapping a button and then the result will be displayed on another screen. The app will look like this…

pda_app

Step 1

Open Xamarin Studio. Click File > New Solution. Select Android App (C#) as the template.

pda1

Step 2

Give your app a name, for example AnimalAgeCalculator. Click Next.

pda2

Step 3

Confirm the project and solution name as well as the project folder location and click Create.

pda3

Step 3

Navigate to the Resources > layout folder and click the cog icon (or right-click the folder). Then Click Add > New File. We will be adding the second screen to the app.

pda4

Step 4

Select Android > Layout, give the new screen a name (eg. Result.axml) and then click New.

pda5

Step 5

Open the Main.axml folder in the Resources > layout folder. Add a Text (Large) element and change the Text value to say ‘Enter your age in years’.

pda6

Step 6

Now add a Plain Text element and change its Id to @+id/ageEditText .

pda7

Step 7

Now add a Text (Medium) element which says ‘Convert to…’. Underneath this, add some Button elements such as those shown below. Change their Text values and Id’s. The buttons below have the following Id’s in order:

@+id/dogButton

@+id/catButton

@+id/goatButton

@+id/hamsterButton

pda8

Save the file.

Step 8

Now open the Results.axml file and add a Text (Large) element – replace its Text value with ‘Result’. Then add a Text (Medium) element, change its Id value to @+id/resultTextView and give it a default Text value (it doesn’t matter what you put here as the result text will change).

pda8b

Step 9

Add some spacing and then a Button element. Rename the Id of this button @+id/backButton and change the Text value to ‘Go back’. Save the file.

pda9

Step 10 

Now click on the project folder (not the solution folder) and click the cog icon (or right-click) > Add > New File.

pda10

Select Activity from the Android list, name it ResultActivity and then click New.

pda11

Step 11

Open the MainActivity.cs file and delete the two sections of highlighted code shown below inside the MainActivity class. This code will not be required in this app.

pda12
Click image to view larger version.

Step 12

In the MainActivity class, define the EditText and Button elements, and create two float variables (age and animalAge) and a string variable (animal) as highlighted on lines 11-18 below. In the OnCreate method, add the following highlighted code (shown in lines 27-31).

pda13
Click image to view larger version.

Step 13 

In the OnCreate method, after adding the EditText and Button elements to the code, start typing dogButton.Click+= to create a button click event and then press the Spacebar key. You will see a list of options – double-click the DogButton_Click option to create a new method of the same name.

pda14
Click image to view larger version.

The new method called DogButton_Click will be created as shown below.

pda14b
Click image to view larger version.

Step 14

Repeat the last step for each button click event. You should now have click events and matching methods for the dog, cat, goat, and hamster buttons. This is where we will start adding code to convert the human years to animal years and take the user to another screen.

pda14c

Add the following code to the methods show below.

pda14d

Step 15

Make sure you have the line of code using Android.Content; at the top section of the MainActivity.cs file’s code.

pda15

Step 16

In the HamsterButton_Click method, change the animal variable’s value to “Hamster” and then create a new intent which will send the values of the animalAge and animal variables to the ResultActivity screen.

pda16

Step 17

The last step will need to be repeated for each button click method as shown below. Just change the value for the animal variable in each method to the appropriate animal as shown below. Save the file.

pda17

Step 18

Open the ResultActivity.cs file and make sure your code is the same as shown in the highlighted areas in the image below. You will need to define the resultTextView and backButton elements as well as get the animalAge and animal values from the Intent created in the MainActivity.cs file. The resultTextView element will display the result of the age conversion (the selected animal name and result in animal years). Save the file.

pda18
Click image to view larger version.

Now just add a click event and method for the backButton element which will take the user back to the main screen when they click on the button which says ‘Go back’.

pda18b
Click image to view larger version.

Step 19

The last step before testing is to go back to the Main.axml file and change the Input Type for the ageEditText element to number. Save the file and test your app.

pda19

Click the Build icon to test your app using an Android simulator.
pda19b

Improving the app

One last thing we can do is prevent any errors from occurring or the app from crashing if the user does not enter a value to convert before tapping a button. We can check if the text field has been left empty and only run the conversion and open the result screen if a value exists in the text input field. Here is an example of this in the HamsterButton_Click method.

pda20

You could repeat this step for all of the button click methods. Now go and test your app again – it should no longer crash if the user does not enter a value in the text field!

Adding click events to a ListView in Android with Xamarin

This tutorial explains how to add click events to items on a list using an Android ListView in Xamarin. In this example, we have a list containing cities in Australia which was made in the previous tutorial. When individual list items are clicked/touched you can have a click event which might take the user to another screen or change the value of a variable, for example.

lv1

Step 1

Open the MainActivity.cs code from the previous tutorial (Creating a Simple ListView in Android with Xamarin) and after the myListView.Adapter = adapter; line start typing in myListView.ItemClick+= and press the spacebar. You will see a list of items to select. Double-click on the MyListView_ItemClick to create a new method of this name.

lvc1
Click the image for a larger version.

You will now have a new method called MyListView_ItemClick. This method will be called when any item on the list is clicked.

Click the image for a larger version.
Click the image for a larger version.

Step 2

Now add an if statement to check which item on the list was clicked/touched. For example, we could check if the ‘Sydney’ list item was clicked or touched. If it was, we can the run the appropriate code for that item. For example, we could take the user to another screen with information about Sydney.

Here is an example. You can just add if statements for each item if it is a small list. If it is a large list, you might like to find a more efficient way of doing it.

if (myListItems [e.Position] == "Sydney") {
                //  code to run when list item clicked goes here
            }

The code that you need to add is highlighted below.

lvc3
Click the image for a larger version.

And that’s it! Now go and try it yourself.

Adding a ListView to an Android app

In this tutorial you will learn how to add a ListView in your Android app using Xamarin. ListView elements allow you to create a scrollable list where each list item can have a click event. A ListView looks like this…

lv1

In this tutorial, we will create the ListView and then we will make each item in the list ‘clickable’ in the next tutorial.

Step 1

To get started, create a new solution in Xamarin (File > New Solution). Choose the Android App template and click Next.

lv2

Step 2

Give your app a name and select Modern Development as the target platform. Click Next.

lv3

Confirm the project and solution name and the project folder location. Click Create.

lv4

Step 3

Open the Main.axml file in the Resources / layout folder. Delete the default button on the screen.

lv5

Step 4

Drag a ListView element on to your screen from the Toolbox. You won’t necessarily see anything on the screen after dragging the ListView on to the screen, so we will look at the code for the Main.axml file in the next step.

lv6

Step 5

Click on the Source tab to view the code for the Main.axml file. Delete the two lines of code that specify the minimum width and height for the ListView element. Then make sure that the layout_width and layout_height properties for the ListView element are both set to “match_parent”.

lv7

Change the name of the ListView to myListView as show below.

lv8

Step 6

Open the MainActivity.cs file. Delete the lines of code highlighted below. They won’t be needed for this program.

lv9

Step 7

Add the following line of code highlighted below to the top section of your code.

lv10

Step 8

We need to create a new List that will contain a list of items of the string data type. It can be called myListItems. We also need to add the ListView to the code called myListView. To do this, add the following two highlighted lines of code in the MainActivity class.

lv11

Step 9

Add the following highlighted line of code inside the OnCreate method so that you can access the ListView item (that you added to the Main.axml screen) in your MainActivity.cs code.

lv12

Step 10

Now you can start adding items to the list called myListItems. Firstly, you need to setup the list (as shown on line 23 below) and then you can add string items to the list. For example, this app will contain a list of cities in Australia. Add the following highlighted lines of code.

lv13

Step 11

In Android development, whenever we want to show a vertical list of scrollable items on a screen we need to use a ListView as we have done. Data in the ListView is populated using an Adapter. The simplest type of adapter we can use is called the ArrayAdapter. The ArrayAdapter will convert an ArrayList of objects into View items that are loaded into the ListView container. This is exactly what we will do here. Copy the two highlighted lines of code below to convert your Arraylist into View items that will be displayed in the ListView in your app.

lv14
Click the image to see a larger version.

That’s it! Now test your app using a suitable virtual Android device (eg. Nexus 5 API 19). In the next tutorial we will add click events for the list items.

lvapptest

Next tutorial: Add click events to a ListView in an Android app

Send SMS from Android app with Xamarin

In this tutorial you will learn how to make an Android app that can send SMS messages. Firstly, we will create a button that can send a pre-determined message to a pre-determined number. We will then extend the app by adding text fields where the user can enter a number and their message.

This is what the app will look like at the end of this tutorial…

smsapp

Step 1

To get started, open Xamarin and click File > New and select Android App from the list of templates. We will be writing this app in the C# language.

sms1

Step 2

Give your app a name. In this example, the app is called SMSApp and Modern Development has been selected as the Target Platform.

sms2

Step 3

Confirm the project and solution name as well as the folder the project will be stored in. Then click on Create.

sms3

Step 4

Open the Main.axml file in the Resources > Layout folder and delete the ‘Hello world, click me!’ button.

sms4

Step 5

Drag a new Button element from the Toolbox on to the screen. Rename its Id to @+id/sendButton and change the Text value to Send SMS.

sms5

Step 6

Now open the MainActivity.cs file to add the code. Delete the code that is highlighted below.

sms6

Step 7 

Click on the Project menu and then select the Project Options (it will be the name of your app project – here it is called SMSApp Options).

sms7

Step 8

Select Android Application from the list and then in the Required Permissions list, check the SendSms option and click on OK. This will allow the app to send SMS messages.

sms8

Step 9

Add the using Android.Telephony; line to the top section of the code.

sms9

Step 10

Define the sendButton as a Button element in your code.

sms10

Step 11

Add the following highlighted line of code to the OnCreate method so that you can access the button element from the screen.

sms11

Step 12

Now create a button click event. Type in sendButton.Click+= then press the spacebar. Double-click the option to create the SendButton_Click method.

sms12

Step 13

Inside the SendButton_Click method, add the following highlighted code.

sms13

There are two values that you need to change. The phone number (shown as 0123456789 above) needs to be changed and also the SMS message contents (shown as Hello world above). Change these values as you like. You can also get values from existing variables here or from user input in text fields. Now go and test your app on a phone with a working SIM card.

Adding user input

Now we will allow the user to enter in a number and a message to send. We will need to add a couple of text labels and text fields to the screen.

Step 14

Open the Main.axml file. Add two Text (Medium) elements and two Plain Text elements as shown below. The Text (Medium) elements should ask the user to enter a number and enter a message.

sms14

Step 15

Rename the first Plain Text element (under Enter a number) to @+id/numberEditText. Rename the second Plain Text element (under Enter a message) to @+id/messageEditText.

sms15a

sms15b

Step 16

Go back to the MainActivity.cs code. Modify the code by adding the highlighted lines of code shown below. You firstly need to define the EditText elements in the MainActivity class (lines 11-12) and then allow the code to access these elements from the screen (lines 22-23). Then you need to modify the SendButton_Click method so that the text entered by the user (the phone number and the desired message) are saved in string variables (lines 31-32). These variables are then used in line 33.

sms16

That’s it! Now go and test your completed app.

Improving on the iOS Temperature Converter App

In this tutorial we will look at how to improve the code in the Temperature Converter App for iOS from the previous tutorial. If you have tested the app yourself, you might notice that the app works great when the user enters only numbers. However, what happens when a user enters nothing or enters something other than numbers (such as a letter or other character)? The app will crash!

We will look at how to prevent such errors from occurring so that the app won’t crash if the user accidentally (or deliberately) enters non-numeric values or nothing at all. This is something known as data validation.

The code below is from the same app but has some new code added to it. All of the code is commented, explaining what each new line does. None of the design elements (buttons, labels, text fields) have been changed in any way.

Sample code

Here is the new and improved code for the ViewController.cs file.

// need to add using System; line to access math functions
using System;

using UIKit;

namespace TempConverter
{
  public partial class ViewController : UIViewController
  {
    public ViewController (IntPtr handle) : base (handle)
    {
    }

    public override void ViewDidLoad ()
    {
      base.ViewDidLoad ();
      // Perform any additional setup after loading the view, typically from a nib.e

      //  Create a button touch event for the Convert to Celsius button
      cButton.TouchUpInside+= CButton_TouchUpInside;
      //  Create a button touch event for the Convert to Fahrenheit button
      fButton.TouchUpInside+= FButton_TouchUpInside;

    }

    void FButton_TouchUpInside (object sender, EventArgs e)
    {
      // Get the temperature entered and store as a string
      string tempString = tempTextField.Text;
      // Check if the string is empty
      if (string.IsNullOrEmpty (tempString) == false) {
        // If string is not empty, create a float variable to store the temperature value
        float temp;
        // Use TryParse method to store the value in the temp variable if value is numeric
        bool isNumeric = float.TryParse (tempString, out temp);
        // Check if tempString value is numeric and if so, use it in the conversion formula
        if (isNumeric == true) {
          // Create fResult variable which stores result of C to F conversion
          float fResult = temp * 1.8f + 32f;
          // Change fResult to decimal data type and round to 2 decimal places
          decimal fResultRounded = Math.Round ((decimal)fResult, 2);
          // Display result on the screen
          resultLabel.Text = fResultRounded.ToString () + " degrees Fahrenheit";
        }
        // If tempString is not numeric, ask user to enter numbers only
        else {
          resultLabel.Text = "Enter numbers only";
        }
      // If nothing was entered by user, ask user to enter a number
      }
      else {
        resultLabel.Text = "Enter a number to convert";
      }

    }

    void CButton_TouchUpInside (object sender, EventArgs e)
    {
      // Get the temperature entered and store as a string
      string tempString = tempTextField.Text;
      // Check if the string is empty
      if (string.IsNullOrEmpty (tempString) == false) {
        // If string is not empty, create a float variable to store the temperature value
        float temp;
        // Use TryParse method to store the value in the temp variable if value is numeric
        bool isNumeric = float.TryParse(tempString, out temp);
        // Check if tempString value is numeric and if so, use it in the conversion formula
        if (isNumeric == true) {
          // Create cResult variable which stores result of F to C conversion
          float cResult = (temp - 32f) / 1.8f;
          // Change cResult to decimal data type and round to 2 decimal places
          decimal cResultRounded = Math.Round((decimal)cResult, 2);
          // Display result on the screen
          resultLabel.Text = cResultRounded.ToString () + " degrees Celsius";
        } 
        // If tempString is not numeric, ask user to enter numbers only
        else {
          resultLabel.Text = "Enter numbers only";
        }
      }
      // If nothing was entered by user, ask user to enter a number
      else {
        resultLabel.Text = "Enter a number to convert";
      }

    }

    public override void DidReceiveMemoryWarning ()
    {
      base.DidReceiveMemoryWarning ();
      // Release any cached data, images, etc that aren't in use.
    }
      
    public override void TouchesBegan (Foundation.NSSet touches, UIEvent evt)
    {
      base.TouchesBegan (touches, evt);

      this.View.EndEditing (true);
    }
  }
}

Creating your first iOS app

This tutorial will show you how to create a Temperature Converter app for iOS devices using Xamarin. We made the same app for Android in a previous tutorial and now we are going to make it for iOS devices. The app will look like this…

iosapp

Although we will be using Xamarin for designing and coding the app, you will still need to have XCode installed on your Mac device (click here for detailed installation instructions).

Watch the video below or scroll down to view the step-by-step instructions and sample code.

Video

Step 1

To get started, open Xamarin and begin a New Solution.

ios1

Step 2

Select App under iOS and then select Single View App (C#). Click on Next to continue.

ios2

Step 3 

Give your app a name. In this case, it will be called TempConverter. You also need to select a minimum iOS version you want to support. In this case, the target version is iOS 9.1. Make sure the target version is either an older or same version of iOS that you will be using to run the app on. Click Next to continue.

ios3

Step 4

Now just confirm the project and solution name (making sure it is not the same name as a solution that already exists in your projects folder) as well as the project folder location and click Create.

ios4

Step 5

Once the new solution has loaded, Xamarin will automatically open a file called AppDelegate.cs. Don’t worry about this file for now as we won’t really be changing anything there. The two files that we will be working with are the Main.storyboard file (for adding the buttons, text labels, and text boxes) and ViewController.cs (for coding the functionality).

ios5

Double-click the Main.storyboard file to open it. It may take a minute to load. The storyboard is where you will add your user interface elements such as buttons, text boxes and text labels. Choose the iPhone device that you want to use as the preview for your storyboard eg. iPhone 6.

ios6

Step 6

In the Toolbox panel (use the search box to find and add the Toolbox to your layout if you don’t see it there), scroll down until you see Label (you can also search in the Toolbox for the Label element.

Drag a Label element on to the phone screen where you would like to place it.

ios7

Step 7

Change the Text value in the Properties panel (on the Widgets tab) to ‘Enter temperature in degrees:’.

ios8

Step 8

Drag the edges of the Label element to resize it so that you can see all of the text.

ios9

You can also change the colour of the text, the font and alignment (eg. align to center) from the Properties panel.

ios10

Step 9

Drag a Text Field element from the Toolbox on to the screen under the text label. Change its Placeholder text to ‘Temperature in degrees’. Resize the Text Field and center-align the text.

ios11

Step 10

Drag two Button elements on to the screen and resize them to fit their text. Change the first button’s text to ‘Convert to Celsius’ and the second button’s text to ‘Convert to Fahrenheit’.

ios12

Step 11

The last element to add is the text label which will display the result of the temperature conversion. Drag a Label element on to the screen and change its default Text to 0, change its Colour and Font size/style. You can also change the Alignment to center.

ios13

Step 12

Now we need to name each of the screen elements so that they can be accessed by the code. Firstly, click on the temperature text field and change its Name to tempTextField.

ios14

Step 13

Now give the ‘Convert to Celsius’ button the Name cButton.

ios15

Also set the Name of the ‘Convert to Fahrenheit’ button to fButton.

ios16

Step 14

Lastly, click on the text label which will display the conversion result and change its Name to resultLabel. Now is a good time to save the Main.storyboard file (Click File > Save).

ios17

Step 15

Now its time to do some coding. Open the ViewController.cs file. In this file, click inside the ViewDidLoad method and add the code highlighted below. This code will add a button touch event that will occur when the user touches to Convert to Celsius button. When we create the cButton.TouchUpInside event it will also automatically create a new method CButton_TouchUpInside which will contain the code that will convert a temperature to Celsius.

ios18

Step 16

We now need to also create a button touch event for the Convert to Fahrenheit button and a method that will contain its code.

ios19

Step 17

Now let’s add the code for the FButton_TouchUpInside method first. This method will be called when the Convert to Fahrenheit button is pressed by the user. Add the highlighted code below. Firstly, a float variable called temp is created to store the temperature value that the user enters into the text field as a float value. Then a variable called fResult will convert the temperature from Celsius to Fahrenheit and store the result as a float value. Lastly, the text on the resultLabel element will display the result and the text ‘degrees Fahrenheit’ at the end of the sentence eg. ’68 degrees Fahrenheit’.

ios20

Note: You may need to resize the fResult label element in the Main.storyboard file so that it can fit the result and text.

Step 18

We can now add the code for the Convert to CButton_TouchUpInside method to run the conversion when the Convert to Celsius button is pressed. Add the highlighted code to this method shown below. Then save your code (File > Save).

ios21

Step 19

Now go back to the Main.storyboard file and select the Text Field element. In the Properties panel and on the Widget tab, scroll down and change the Keyboard Type to Decimal Pad so that numbers with decimal place can be typed in and the most suitable keypad is displayed. Save the file.

ios22

Step 20

At this point, the app will work and will allow the user to type in a temperature (as a whole or decimal number) and convert it to either Celsius or Fahrenheit. However, after the user has typed in a number they should be able to hid the keyboard if it is no longer needed.

Before testing the app we will add a little piece of code that will allow the keypad to be dismissed by the user when it is no longer needed. To do this, go back to the ViewController.cs file and start typing the highlighted line of code (where it is shown below). As you start typing override touchesBegan you should see an auto-complete suggestion called TouchesBegan(NSSet touches, UIEvent evt). Press the Enter/Return key on your keyboard to auto-complete the line of code. This will create a new override method called TouchesBegan. Inside this method we will add some code to dismiss the keyboard.

ios23
As you start typing override touchesBegan you should see an auto-complete suggestion called TouchesBegan(NSSet touches, UIEvent evt). Press the Enter/Return key on your keyboard to auto-complete the line of code.

Add the following code inside the new override method called TouchesBegan to allow the keyboard to be dismissed when typing has been completed by the user. Then save the file.

ios24

Finishing up

All of the coding is done. Congratulations – you have made your first iOS app using Xamarin and the C# programming language! Remember to save your files.Now just select a type of iPhone model you would like to test this app on and click on the Build button to start testing/emulating the app.

ios25

And this is what the completed app should look like…

ios26

What next?

Test your app thoroughly. Are there any problems with your app? Does it crash under some circumstances? Is there any way it could be improved. Jump into the next tutorial to see how this app can be improved.

Sample code

You can download the sample code for the ViewController.cs file here:

using System;

using UIKit;

namespace TempConverter
{
  public partial class ViewController : UIViewController
  {
    public ViewController (IntPtr handle) : base (handle)
    {
    }

    public override void ViewDidLoad ()
    {
      base.ViewDidLoad ();
      // Perform any additional setup after loading the view, typically from a nib.e

      cButton.TouchUpInside+= CButton_TouchUpInside;

      fButton.TouchUpInside+= FButton_TouchUpInside;

    }

    void FButton_TouchUpInside (object sender, EventArgs e)
    {
      float temp = float.Parse(tempTextField.Text);
      float fResult = temp * 1.8f + 32f;
      resultLabel.Text = fResult.ToString () + " degrees Fahrenheit";
    }

    void CButton_TouchUpInside (object sender, EventArgs e)
    {
      float temp = float.Parse (tempTextField.Text);
      float cResult = (temp - 32f) / 1.8f;
      resultLabel.Text = cResult.ToString () + " degrees Celsius";
    }

    public override void DidReceiveMemoryWarning ()
    {
      base.DidReceiveMemoryWarning ();
      // Release any cached data, images, etc that aren't in use.
    }
      
    public override void TouchesBegan (Foundation.NSSet touches, UIEvent evt)
    {
      base.TouchesBegan (touches, evt);

      this.View.EndEditing (true);
    }
  }
}

Publishing your Android app

This tutorial explains how to publish your app and create an .APK file that can be installed on an Android phone. For this tutorial, we will be using the CookieClicker app. You might also want to change the app icon and details before publishing your app.

Watch the video below or scroll down to read the step-by-step instructions.

Video

Step 1

To get started, open the solution that you wish to publish in Xamarin. You will need to create an Android Signing Key before you can publish your app. To do this, click on the Xamarin Studio Community menu and select Preferences (this might be on the File menu in Windows).

p1

Step 2

In the Preferences dialog, click on Android Signing Keys (under Publishing) and click on Create New Key.

p2

Step 3

Give your new signing certificate an alias (name) and create a password (at least 6 characters long). Then select the validity length (how many years the certificate will be valid for) and fill in at least of the text boxes with something (eg. just provide your name or your city name). Click on OK to continue.

p3a

You should then see your new signing key/certificate in the list of Android Signing Keys. Click on OK to exit the Preferences dialog.

p3b

Step 4

Select the Project menu and change your Active Configuration to Release. This will allow you to publish your app (you can change this back to Debug after you have published your app so you can return back to coding and testing your apps).

p4

Step 5

Select the Build menu and then click Archive for Publishing.

p5

Step 6

Now click on Sign and Distribute.

p6

Then select Ad-Hoc to save the app file (the .apk file) to your computer. Click on Next.

p7

Step 7

Select your signing key from the list and click Next.

p8

Then confirm you are happy with the app details and file size and click Publish.

p9

Step 8

Lastly, choose where to save your .apk file and click on Save. You can now share this file online or copy it to your phone (either by USB cable or email). You can also upload it to the Google Play store for other people to download.

p10

Step 9

After you have published your app, remember to change the project’s active configuration back to Debug by clicking on the Project menu > Active Configuration > Debug.

Important note

If you decide to upload your app to the Google Play store you must make sure that you do not violate any copyright laws (eg. check that you are not using other people’s images or sound files and that you app is not the same as an existing app). Also, make sure you have your parents’ permission before uploading any apps to the Google Play store.

Making a Cookie Clicker game for Android

For our second Android app project, we will create the most pointless but addictive game in the world…a cookie clicker! A basic version of it will look like the image shown below, but you can extend this game as much as you like. You will also learn how to add image buttons to your app screens.

cc1

Watch the video below or scroll down to read the step-by-step instructions and view the sample code.

Video

Step 1

You will need to create a new Android App solution in Xamarin called CookieClicker. Click on New Solution (or File > New Solution) to get started.

cc2

Step 2

Choose Android App as the type of new solution and then click Next.

cc3

Step 3

Set the App Name to CookieClicker (one word – no spaced). Choose Modern Development as the Targeted Platform using the default theme and click on Next.

cc4

Step 4

Keep the project and solution names as CookieClicker, select a project location to store your files in and click on Create.

cc5

Step 5

Open the MainActivity.cs file (if it does not automatically open) and delete the lines of code highlighted below. These lines of code won’t be needed for this project.

cc6
Click to see larger version of this image.

Step 6

Now open the Main.axml file located in the Resources > layout folder.

cc7

Step 7

Click on the button that says “Hello World, Click Me!”. We won’t need this button so it can be deleted. Either click on it and press the Delete key on your keyboard, or right-click the button and select Delete.

cc8

Step 8

From the Toolbox (if you don’t see it, you can search for the Toolbox from the search bar), scroll down under Images & Media and drag an ImageButton element on to the phone screen.

cc9

Step 9

Now you will need to download a cookie image to your computer (preferably a PNG image file with a transparent background). A free public-domain image has been provided below. Click on the image to open the full-size version and then save the image to a folder on your computer and name it cookie.png.

Click to open the full-size image. Image from: https://pixabay.com/en/chocolate-chip-cookies-dessert-304801/ (CC0 Public Domain - free for commercial use, no attribution required)
Click to open the full-size image. Image from: https://pixabay.com/en/chocolate-chip-cookies-dessert-304801/ (CC0 Public Domain – free for commercial use, no attribution required)

Step 10

Select the ‘drawable’ folder inside the Resources folder and click on the small cog icon. Then select Add > Add Files from Folder.

cc10

Step 11

Select the folder that contains the cookie image file and click on Open.

cc11

Step 12

Select the cookie.png file (or whatever yours is called) and make sure the checkbox is checked. Then click on OK.

cc12

Step 13

Make sure you select Copy the file to the directory and then click on OK.

cc13

Step 14

Now you should see cookie.png in the drawable folder.

cc14

Step 15

Click on the ImageButton element on the phone screen and change the Src property to @drawable/cookie (you do not need to include the .png file extension).

cc15

Step 16

Now we need to make sure the image fits properly on the screen. Click on the drop-down arrow next to the Scale Type property and change it to fitCenter.

cc16a

You can then also click on the ImageButton and drag the little circle up to change the height of the image. You can also change the width of the image this way. Alternatively, go to the Layout tab on the Properties panel and change the width and height values there eg. 435dp for the height. Note: sizes of elements are measured using the ‘dp’ unit on Android.

cc16b

cc16c

If you go to the Source tab, your code for the Main.axml file might look like the code shown below. However, your code could be a little different so don’t change the code here unless you are sure you know what you are doing.

cc16d

Step 17

In the Designer view, drag a Text (Large) element on to the phone screen under the ImageButton. This will be used to display the number of clicks.cc17

Step 18

From the Widget tab on the Properties panel, change the Text value from Large Text to 0 clicks. At the same time, change its Id from @+id/textView1 to @+id/cookieTextView . You can also change the Gravity value to center so the text is centered.

cc18

Step 19

Click on the ImageButton element (the cookie) and change its Id from @+id/imageButton1 to @+id/cookieImageButton – now you need to save the Main.axml file.

cc19

Step 20

Now we can add the code! Open the MainActivity.cs file and create an integer variables called clicks that is given an initial integer value of 0. This variable will be created inside the MainActivity class, as highlighted below.

cc20

Step 21

We also need to define the ImageButton element and the TextView element in the code. This is highlighted in the lines below. Make sure to use the correct names for each element.

cc21

Step 22

Inside the OnCreate method (under the SetContentView (Resource.Layout.Main); line), we need to now setup the ImageButton and TextView element.

cc22

Step 23

The next thing you need to do is create a click event for the cookie ImageButton by adding the line cookieImageButton.Click+= CookieImageButton_Click; – this will create a new method called CookieImageButton_Click which will contain the code that will increase the number of clicks and display the number of clicks each time the ImageButton is tapped.

cc23

Step 24 

Inside the CookieImageButton_Click method, add the following two highlighted lines of code. The clicks++; line will increase the clicks variable by 1 each time the button is tapped, and the next line of code is responsible for converting the clicks variable value to a string and displaying the clicks variable’s value on the screen as well as the text “clicks!” at the end eg. 25 clicks!

cc24a

Now save your work. All of the coding is done! Now you could extend this app by adding extra buttons to purchase items when a certain number of cookies are clicked (using if statements) or increase the number of cookies by a different amount. You could add extra text labels or buttons too. However, let’s test that this app works properly first. Click on the Build button after selecting a virtual device to run the app on (if you don’t know how to do this, refer to the previous tutorial – Creating your first Android app with Xamarin).

cc25a

cc25b

Here is the source code for the MainActivity.cs file:

using Android.App;
using Android.Widget;
using Android.OS;

namespace CookieClicker
{
  [Activity (Label = "CookieClicker", MainLauncher = true, Icon = "@midmap-hdpi/icon")]
  public class MainActivity : Activity
  {
    int clicks = 0;

    ImageButton cookieImageButton;
    TextView cookieTextView;

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

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

      cookieImageButton = FindViewById<ImageButton> (CookieClicker.Resource.Id.cookieImageButton);
      cookieTextView = FindViewById<TextView> (CookieClicker.Resource.Id.cookieTextView);

      cookieImageButton.Click+= CookieImageButton_Click;

    }

    void CookieImageButton_Click (object sender, System.EventArgs e)
    {
      clicks++;
      cookieTextView.Text = clicks.ToString () + " clicks!";
    }
  }
}