Tag Archives: first

Creating your first Android app with Xamarin

This tutorial explains how to use Xamarin and the C# programming skills you have gained so far in this tutorial series to start making your very own Android apps. In this tutorial, we will develop a Temperature Converter app for Android which can convert between Celsius and Fahrenheit temperatures.

This is what the app will look like:

Temperature Converter app for Android
Temperature Converter app for Android

So let’s get started! You can watch the video below or read through the step-by-step instructions below. The C# sample code for this project is also at the bottom of this page.

Video

Step 1

Click on New Solution to create a new solution for this project.

aa1

Step 2

Select the Android App template and click Next.

aa2

Step 3

Give your app a name. For this example, we have called the app TemperatureConverter. Select a target platform. Here, we have chosen Modern Development to make this app compatible with modern Android phones. If you choose Latest and Greatest you will need to download the latest Android Simulators. Choose Default theme and click Next.

aa3

Step 4

Choose the location to store your project and click Next. You can keep the project name as it is or give it a different name.

aa4

Step 5

After Xamarin creates your new project it will most likely automatically open the MainActivity.cs file (if not, double-click it from the Solution folders list on the left side of the screen). By default, you will already have some lines of code in there for an example app. Delete the lines of code shown in the image below (we will be adding our own buttons so we don’t need the one that is already there).

aa5

Step 6

In the Solution list on the left side of the screen, click to open the Resources folder, then open the layout folder, and double-click to open the Main.axml file. This will open the storyboard for our main screen in Designer view.

aa6

You will see the default button ‘Hello World, Click Me!’ there. You can right-click this button and click on Delete to remove the button.

aa6b

Step 7

From the Toolbox on the right side of the screen, scroll down until you see the Text (Small) element (under Form Widgets). Drag the Text (Small) element on to the storyboard in the Designer view.

aa7

Step 8

Now drag a Plain Text element (under Text Fields) from the Toolbox on to the storyboard under the Small Text element you added in the previous step.

aa8

Step 9

Now you need to drag two Button elements (found under Form Widgets in the Toolbox) on to the screen.

aa9

Hint: You can search form screen design elements in the Toolbox using the search box.

Step 10

The last screen design element to add is a Text (Large) (large text label) to display the result of the temperature conversion.

aa10

Step 11

Click on the Small Text element and in the Properties panel (and Widgets tab) change the Text property from ‘Small Text’ to ‘Temperature (in degrees)’. Hit the Enter/Return key on your keyboard and you should see the text label change on the phone screen.

aa11

Step 12

Change the Text property in the Properties panel for both buttons. The first button should say ‘Convert to Celsius’ and the second button should say ‘Convert to Fahrenheit’.

aa12

Step 13

Now change the large text label so that it says ‘0’ is the default value before any result is displayed.

aa13

Did you know? These values can also be changed from the Source view if you prefer as shown below. Be careful not to accidentally change any of the other code though! Some of your code might be different to the code below – don’t change it unless you know exactly what you are doing.

You can alternatively change the text and IDs of elements in the Source view if you prefer that over the Designer view.
You can alternatively change the text and IDs of elements in the Source view if you prefer that over the Designer view.

Step 14

Now that we have changed the text that displays on the labels and buttons, we need to change the actual names of the elements.

Click on the temperature text field and change its Id in the Properties panel. Its Id needs to change from @+id/editText1 to @+id/temperatureEditText.

aa14

Step 15

Now change the name (Id) of the text label that will display the conversion result. Click on the result label and change its Id from @+id/textView2 to @+id/resultTextView.

aa15

Step 16

Repeat the last step for the two buttons changing their Id’s to @+id/cButton for the Convert to Celsius button and @+id/fButton for the Convert to Fahrenheit button. Make sure you save the Main.axml file by pressing Cmd + S (on Mac) or Ctrl + S (on Windows).

aa16

Step 17

Now we can add the functionality to the app. Open the MainActivity.cs file. Firstly, we will define the different text label and button elements in the code. Inside the public class MainActivity: Activity class, add the following highlighted code:

aa17
Click to see larger version of image if you can’t read the code.

Step 18

Now we need to assign the values from the Main.axml file to each element in the MainActivity.cs file. Under the SetContentView (Resource.Layout.Main); line of code, add the following highlighted code:

aa18

Now we will be able to use these elements in a new method that will convert the temperature input.

Step 19

We need to create click events for both the ‘Convert to Celsius’ button and the ‘Convert to Fahrenheit’ button. To do this, add the code below. You will notice that this will create two new methods for our click events. These methods will be used when the click event is fired (when the buttons are tapped by the user) so the relevant conversion code will need to be in each click event method.

aa19

Step 20

Now let’s add the code for the FButton_Click method first (the method which will convert from Celsius to Fahrenheit). We will create a new float variable that will contain the value entered by the user in the temperatureEditText text field. The value will also need to be converted (parsed) from the string data type to the float data type.

aa20

Step 21

A float variable will need to be created that will store the result of converting from Celsius to Fahrenheit. In the conversion formula, we need to add the letter f at the end of each value that will need to be parsed as a float.

Step 22

Now we can access the resultTextView element and display the conversion result on that text label. It will also need to be converted to a string. We can add the text “ degrees Farenheit” to the end of the result displayed.

Step 23

Now we just need to write the code for the CButton_Click method by creating the variable which will store the value entered by the user, creating a variable which will store the Fahrenheit to Celsius conversion result, and then displaying the result on the text label. After adding the code (as shown below), save the file.

aa23

Step 24

Now go back to the Main.axml file in the Designer view and click on the temperatureEditText text field element. In the Properties panel, scroll down until you see Input Type (under Input Format on the Widget tab). Change the Input Type to NumberDecimal. Then save the file.

aa24

That is all of the coding done! Now we can test the app but first we must select an Android Virtual Device to emulate the app.

Step 25

Click on the Device button next to Debug on the top toolbar and select a compatible Virtual Device that has been installed. The Virtual Device must be the same or higher API level than the targeted device selected in Step 3 (eg. the Modern Development option is API level 16). The Nexus 5 virtual device shown below is API level 19. If you don’t have a compatible virtual device to select then you will need to click on Manage Android Devices and download a compatible virtual device (they are free to download).

To install and use virtual Android devices for testing, it is suggested you install the Xamarin Android Player. Once installed, you can download a virtual device (eg. Nexus 5) and use it on your Mac or PC to test the Android apps you build. You can also use the built-in Android Virtual Device manager but it is much slower!

aa25a

Once a compatible virtual device has been selected you can run the app by clicking on the Build icon on the top toolbar.

aa25b

The Xamarin Android Player will open and load the selected virtual device. It may take a minute. Unlock the device screen and your app should open!

aa25c
Unlock the simulated phone by dragging the padlock icon to the side. Your app should then automatically open.
aa25d
Enter a number value in the text field and then press the relevant conversion button to see the conversion result.
Success!
Success!

Congratulations, you just made your very first Android app using Xamarin and the C# language! In the next tutorial we will make the same app for an iPhone.

Later on we will also look at how to export an Android app so that you can install it on your own phone.

Sample C# code

Here is the sample code for the MainActivity.cs file. Note that the app, solution and project are all named TemperatureConverter.

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

namespace TemperatureConverter
{
  [Activity (Label = "TemperatureConverter", MainLauncher = true, Icon = "@mipmap/icon")]
  public class MainActivity : Activity
  {
    Button cButton;
    Button fButton;
    TextView resultTextView;
    EditText temperatureTextEdit;

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

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

      cButton = FindViewById<Button> (TemperatureConverter.Resource.Id.cButton);
      fButton = FindViewById<Button> (TemperatureConverter.Resource.Id.fButton);
      resultTextView = FindViewById<TextView> (TemperatureConverter.Resource.Id.resultTextView);
      temperatureTextEdit = FindViewById<EditText> (TemperatureConverter.Resource.Id.temperatureTextEdit);

      cButton.Click+= CButton_Click;
      fButton.Click+= FButton_Click;

    }

    void FButton_Click (object sender, System.EventArgs e)
    {
      float temp = float.Parse (temperatureTextEdit.Text);
      float fResult = temp * 1.8f + 32f;
      resultTextView.Text = fResult.ToString () + " degrees Fahreheit";
    }

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

 

PIP Map Effect in Unity

In this tutorial we will look at how to use a picture-in-picture (PIP) effect to display a map in the top corner of the screen. The map allows a player to see where they are located in the game world and where nearby landmarks, objects or other players are.

The image below shows a game with a first person view as the main camera, and a PIP effect showing the player’s location on the game map in the top right corner of the screen.

A picture-in-picture (PIP) map in a first-person view game.
A picture-in-picture (PIP) map in a first-person view game.

Watch the video below to see how you can add a PIP map effect to your game in Unity.

In this scene you can’t actually see the red sphere in the first person view because the character is inside the sphere. However, if you were using a third person view, you would probably see the sphere. In this case, you would want to hide the sphere on the first person camera and only show it on the map camera. This is possible to achieve with the use of layers which is what we will look at in the next tutorial.

Tip: You might want to have the object that represents a blip on the map to be higher so that it is still visible if a character goes inside a building or cave or under another object.

Go further

See if you can work out how to have the map camera follow the player around so that their blip doesn’t disappear off the map. This is something you will need to know if you have large scenes where the camera does not cover the entire scene.

Character Controllers in Unity

Unity has built-in character controllers that allow you to jump right into your game so that you can see what it will look like when the user is playing it. Unity includes a first person and third person controller. In this tutorial, you will learn how to add a first person controller to your scene.

You can easily add a first person character controller to your game scene using the Characters asset package. Adding a first person character controller to your game is a great way of seeing what your world looks like up close as a character.

First person character controller in Unity.
First person character controller in Unity.

It is not until you see the world from a character’s perspective that you might realise that some hills are too steep, or there are too many trees, or the grass is too thick. You can then go and make any necessary changes to your project.

Note: The frame rate of this video is very low. The actual quality of the game is much better than it looks!

Pseudo classes

Pseudo classes are used to specify a special state of a particular element. For example, the first letter in every paragraph could be a different size, or a link changes colour when the mouse cursor moves over it. Pseudo classes are built into CSS. You can’t just make your own pseudo classes. In this tutorial we will look at styling first letters and first sentences of paragraphs, how to style the first and last child of a parent, and also how to add content before and after the existing content in an element.

Watch the video below to see how to use pseudo classes in your CSS, then scroll down to see the sample code for the different examples.

The HTML code below is for the first example in the video (styling the first letter and styling the first sentence in paragraphs):

<!DOCTYPE html>
<html>
<head>
 <title>Pseudo classes</title>
 <meta charset="utf-8"/>
 <link rel="stylesheet" href="resources/stylesheet8.css" type="text/css"/>
</head>
<body>
 
<p>The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.
</p>
 
<p>The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.
</p>
 
<p>The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog. The quick brown fox jumped over the lazy dog.
</p>
 
</body>
</html>

And here is the CSS code for the first example:

p:first-letter{
 font-size:150%;
 font-weight:bold;
 color:red;
}
 
p:first-line{
 color:blue;
}

This is the HTML code for the second example (styling first child and last child, and styling before and after):

<!DOCTYPE html>
<html>
<head>
 <title>More pseudo classes</title>
 <meta charset="utf-8"/>
 <link rel="stylesheet" href="resources/stylesheet9.css" type="text/css"/>
</head>
<body>
<p>This is a paragraph</p>
<div id="parent">
 <p>The quick brown fox jumped over the lazy dog.</p>
 <p>The quick brown fox jumped over the lazy dog.</p>
 <p>The quick brown fox jumped over the lazy dog.</p>
 <p>The quick brown fox jumped over the lazy dog.</p>
</div>
</body>
</html>

And here is the CSS code for the second example:

#parent p:first-child{
 color:green;
 text-decoration:underline;
 font-weight:bold;
}
 
#parent p:last-child{
 color:red;
 text-decoration:none;
 font-style:italic;
}
 
#parent p:before{
 content:"-->";
}
 
#parent p:after{
 content:"<--";
}

 

Blinking LED Arduino project

This video tutorial has been designed for those just starting out with Arduino. For this beginner project you will need an Arduino Uno board (or compatible board), an LED of any colour, a 470-Ohm resistor, two jumper wires, a breadboard, a male A-B USB cable, and a computer (Mac/Windows) with the Arduino IDE software installed.

This project involves programming your Arduino Uno to make an LED light blink on and off. To get started, watch the video below or click here to view it on YouTube. Access the links below to get a copy of the code, printed instructions, schematic, and a guide to resistors.

Downloads:

The source code is also available here:

/*
 Blink
 Turns on an LED on for one second, then off for one second, repeatedly.
*/
 
// Give the LED a name - it will be connected on PIN 13
int led = 13;
 
// the setup routine runs once when you press reset:
void setup() { 
 // initialize the digital pin as an output.
 pinMode(led, OUTPUT); 
}
 
// the loop routine runs over and over again forever:
void loop() {
 digitalWrite(led, HIGH); // turn the LED on (HIGH is the voltage level)
 delay(1000); // wait for a second (1000 = 1 sec.)
 digitalWrite(led, LOW); // turn the LED off by making the voltage LOW
 delay(1000); // wait for a second
}

Photos

1 2 3 4