Tag Archives: app

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

Add a relative layout to an Android screen in Xamarin

In the tutorials so far, we have been designing Android app screens in Xamarin using a Linear Layout. A Linear Layout basically arranges buttons, text views, text fields and other elements within boundaries. These elements are usually stacked. However, Relative Layouts allow us to position elements relative to each other.

image11

Note: If you change to a Relative Layout, you will need to add elements to your screen through code instead of dragging and dropping items on from the toolbox. It is best to drag all of the elements on that you need (eg. buttons, text boxes), and then switch to a relative layout.

This tutorial assumes you already know how to create an Android app project in Xamarin. If you don’t know how to, then go back to the first tutorial.

Step 1

Open the Main.axml file (in the Resources > layouts folder) for your Android app in Xamarin. Drag a few elements on to your screen (eg. three buttons as shown below).

image4

Step 2

Click on the Source tab. Remove any gravity properties from the linear layout and remove the android:orientation=”vertical” line. Where the code says LinearLayout, replace it with RelativeLayout (both in the opening and closing tags).

image5

Go back to the Designer view and you will notice that all of the buttons are now on top of each other.

image6

Step 3

Go back to the Source tab and start typing a new line inside the Button tag for the first button. Start typing layout and you will see many options to select from. Select the android:layout_below option by double-clicking it or press Enter.

image7

Complete the line by typing android:layout_below=”@id/button1” and then close the button tag using />  …this will set the second button to be positioned below the first button. Do the same for the third button but set it so it is placed under the second button (replace @id/button1 or @id/button2 with the names of your buttons/elements).

image8

Now go back to the Designer view and you should see the three buttons placed below each other as shown below.

image9

Experiment with the different layout options from the list, for example layout_toRightof will place an element to the right side of another element.

image10

This is what the screen will look like when button2 is set to be placed to the right of button1.

image11

That’s it! You can use different combinations of layout properties to arrange the elements on your screen and position each element in relation to other elements.

Adding thumbnail images to list rows in the iOS List App with Xamarin

This tutorial will show you how to add a thumbnail image to each row of the Cities list in the iOS List app we made in the previous two tutorials. This is what the app will look like…

image1

Step 1

To get started, open the Main.storyboard file in the iOS List App solution. Resize the labels on the table row on the main screen and move them to the right side of the table row. Then drag an ImageView element from the toolbox on to the left side of the table row. Change the ImageView element’s name to cityImageView.

image2

Step 2 

Make sure you have added your images to your project (this was explained in the previous tutorial).

image3

Also make sure you have added public string ImagePath; to your code as seen on line 76 of the CitiesViewController.cs file below (this was also explained in the previous tutorial).

Click image to see larger version.
Click image to see larger version.

For each city in your list, you should also have specified the ImagePath value (location of the image and its filename) in the CitiesViewController.cs file.

Click image to see larger version.
Click image to see larger version.

Step 3

In the CityTableViewCell.cs file, add the following highlighted line to set the image displayed for each row of the City class. This will get the images to display on each row. Save all of your files.

image6

Step 4

Now just go and test your app. This is what the thumbnail images should look like:

preview

Adding a Details screen to the List app for iOS with Xamarin

In this tutorial, we will look at how to extend the iOS List app we made in the previous tutorial by adding a Details screen that will display more details about item the user has selected from the list.

This is what the app will look like…

detailsscreen

Note: The title bar of the app will normally display and should be presented when the app is tested on an actual iOS device, but a bug in the iOS Simulator used here prevents the title bar from showing.

Step 1

Drag a Navigation Controller from the Toolbox on to your storyboard.

image3

Right-click and Delete the Root View Controller that is not required (you may have to delete twice).

image4

Step 2

Hold down the Control (Ctrl) key while clicking and dragging from the Navigation Controller to the Table View screen. Then select Root.

image5

Step 3

Drag a View Controller from the Toolbox on to your storyboard next to the main screen.

image6

Step 4

Add an ImageView element and a Label element to your screen. The default Text value for the label can be set to City Name. You also need to give both elements a name. Set the Name value for the Image View to cityImageView and the Name value for the label to cityNameLabel.

image7
When you give the ImageView or Label element a name you will see a yellow warning icon in the Name field. Click this icon and then type in DetailsViewContoller and press the Enter key to generate a new class and codebehind for this screen.

image8

Step 5

Now Control-click (Crl + click) and drag from the row on the main screen to the new details screen and select Show. This means that when the user selects a city from the list, they will be taken to the city details screen.

image9

You can also double-click on the main screen’s title to change it.

image10

Step 6

Click on the arrow between the main screen and details screen. On the Properties panel, set the Identifier value to DetailsSegue. Remember its name because it will be used in the code.

image11

 

Step 7

Open the CitiesViewController.cs file and scroll down to the City class. We need to add a new property called ImagePath which will contain the image for each city in the class.

image12

 

Step 8

Right-click the project folder and select Add > New Folder. Name this folder Images.

image13

Now right-click the Images folder and click Add > Add Files from Folder.

image14

Browse for the folder containing your images and then click Open.

image15

Select the desired images and then click OK.

image16

Select Copy the file to the directory and Use the same action for all selected files. Then click OK.

image17

Step 9

Go back to the CitiesViewController.cs file and for each city in the cityList, add the lines highlighted below to specify the ImagePath for each city’s image. Remember to add a comma to the end of the line before the ImagePath line (see the commas at the end of lines 22 and 31).

image18

Step 10

Go to the DetailsViewController.cs file and add the public City selectedCity; line to the DetailsViewController : UIViewController class. Save the file.

image19

 Step 11

Now you need to add a PrepareForSegue override method. You can add this method after the GetCell method. Start typing public override PrepareForSegue and then select the PrepAreForSegue method from the list by double-clicking it or pressing Enter to autocomplete.

image20

Step 12

Add the following code to the new PrepareForSegue method. This will check if the segue is the DetailsSegue (in other words, if the user tapped one of the rows from the table on the main screen that takes them to the details screen). Then it will get the relevant data from the selected row to be displayed on the details screen.

image21

Step 13

Back in the DetailsViewController.cs file, add a public override ViewWillAppear method. To do this, start typing public override ViewWillAppear and then select that method from the list.

image22

Step 14

Inside the new ViewWillAppear method (which runs as soon as the second screen loads), add the following highlighted lines of code (replacing any existing default code inside the method). This will set the label text to display the name of the selected city and will also set the ImageView to display the image representing the selected city.

image23

All done! Make sure you save your files and then you can test your app!

You can extend this app by adding more properties to each City item so that the Details page can display more information about a city such as points of interest, activities, and even its location on a map.

In the next tutorial we will look at how to add thumbnail image previews to each row in the list.

Creating a List app for iOS with Xamarin

In this tutorial, we will look at how to create a list app for iOS. The example used in this tutorial will be a list of cities. When the name of a city in the list is tapped by the user, details about that city will be presented (we will achieve that part in the next tutorial).

image1
The iOS list app.

Step 1

Begin by clicking File > New Solution in Xamarin Studio and then select iOS App and Single View App. Then click Next.

image2

Step 2

Give the app a name (the app in this example will be called ListAppIOS), select the target iOS version and then click Next.

image3

Step 3

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

image4

Step 4

Open the Main.storyboard file and select an iPhone model from the View As drop-down list (eg. iPhone 6).  Then drag a Table View Controller on to the storyboard next to the main screen.

image5

Step 5

Now right-click on the main screen (on the left) and select Delete to remove this screen as it is no longer needed (you may need to click Delete twice). The Table View controller will now be the first screen that loads when the app launches.

image6

Step 6

Now that the first screen is deleted, the ViewController.cs file will no longer be needed so we can delete it. Select the ViewController.cs file, right-click it and select Remove.

image7

Then select Delete when the dialog box appears asking you.

image8

Step 7

Now you will need a class that will control the table view controller. Select the Table View Controller by clicking on the bar at the bottom of it. You should see the Class property on the Properties panel. At the moment it is empty but it needs a class so we can create the class here.

image9

Click in the Class property field and type in a name for the new class eg. CitiesViewController. Then press Enter. You’ll notice a new C Sharp (.cs) file is created for this new class and it will appear in the solution panel.

image10

At this stage, if you simulate the app you will see an empty list on the main screen as shown below.

image11

Step 8

Now go back to the Main.storyboard file and click on the title bar at the top of the app screen. We need to add a reuse identifier that allows the app to re-use rows on the table on the app screen as the user scrolls down the screen rather than having to generate new rows. Change the Identifier value to City.

image12

Step 9

Now open the CitiesViewController.cs file so that you can start populating a list of cities in the table view controller. Adding the using System.Collections.Generic; line allows us to use the List class that can contain many elements. Before we start creating a list of cities we need to define what a city is by creating a City class and giving it some properties such as its name (string), the country and state it belongs to (strings) and its population (integer).

image13

Step 10

Once we have created the class City, we can create a List that will contain many elements and set its type to City so that every time added to the list will be a city. First we give the list its name and set its type, and then we can create the list.

image14

Step 11

Now that we have create the list, we can populate the table view with data from the list.

image15

Step 12

Now we need to override a few of methods: NumberofSections, RowsInSection, and GetCell. For each method, as you type public override and press the spacebar key, you will be presented with methods that you can select from. Start typing the name of the method you want to override and then double-click it to add the override method.

The first method we override is NumberofSections which can be set to return 1 because only one section is needed in the table. As shown below on line 36, we set return to 1.

The second method is RowsInList which is set to return CityList.Count; (this will make as many rows in the table as there are cities in the list) as seen on line 41.

The third method we override is GetCell which is the method that will allows us to get a re-usable cell, modify its values, and return it to the table view. We create a variable called cell and we use the name of the reuse identifier we set for the table view controller back in Step 8 (line 46). We also create a variable called data which set each row to contain data from the city list (line 47) and we set the text on the TextLabel (a default TextLabel already exists) for the cell to be the name of the city for that row (line 48). Lastly, we return cell (line 49).

Here are the three methods once they have been added.

image16
Click the image to see a larger version.

Step 13

At this stage, if you test the app in the simulator you will see the list with the name of each city on each row of the list (we only have two rows in this list but you can add many more to your list).

image17

Now we need to customised the rows in the list to improve their appearance and so they can display some more information about each city.

Step 14

Now we will add more details to each row in the table view (the state and country). Open the Main.storyboard file and click once on the row at the top of the table view. Go to the Class field. We will create a class that will represent the row.

image18

The Class field should currently say UITableViewCell (if it says UITableView, then you may have clicked twice on the row on the screen. De-select the row, then click it once making sure that that the Class field says CityTableViewCell. Type in CityTableViewCell in the Class field and press the Enter key on the keyboard.

image19

You should now see the CityTableViewCell.cs file in the solution panel. Double-click it to open the file – we will now start adding code to this new C Sharp file.

image20

Step 15

Now we need to create a local private variable called City just for this class. Then we need to create a global variable for this data so it can be accessed anywhere. In this, we will have a getter which will get the method that we will access the value of the property (it will return bookData – the private property). Then we set the bookData to the value we are getting.

image21

Go back to the Main.storyboard file. Drag a Label element on to the row at the top of the screen.

image22

Resize the row at the top of the screen because it will need to fit more labels by dragging it down from the circle at the bottom of the row.

image23

Step 16

Now add more Label elements to the screen to display the city name, state name, country name, and population. Arrange and resize the labels so they will be able to fit their text in. Give each label a default property for Text so that you know what each label represents. You can also change the colours or font style. For example, the city name label below is set to Size 19pt Semibold.

Change the Name property for each Label. The labels on this screen have the following names:

  • cityNameLabel (this will display the city name)
  • stateCountryLabel (this will display the state and country separated by a comma)
  • populationLabel (this will display the city’s population)

image24

Step 17

Go back to the CityTableViewCell.cs file. We now need to access the labels from the screen that we created in Step 16 and set the text on the labels to match the properties from cityData when the the cityData property receives its value. Add the lines of code below and then save the file.

Note that the state and country are added together with a comma and space in between them. Also note the #,##0 inside the ToString() brackets – this will place commas between the hundreds and thousands for population when displayed on the populationLabel to improve formatting.

image25
Click the image to see a larger version.

Step 18

Go back to the CitiesViewController.cs file. Instead of simply getting a cell, we will now get a cell as CityTableViewCell so we need to add the extra code to the GetCell method as highlighted on line 46 of the code below.

image26
Click the image to see a larger version.

We also need to change the code so that instead of having cell.TextLabel.Text = data.Name; we will now just have cell.cityData = data;

image27
Click the image to see a larger version.

This means we are no longer accessing a property of the data but instead we are just passing the city. Now it is time to test the app. When you test your app in the simulator you may notice some problems with the formatting of your rows such as the row height or overlapping text as seen below. We will look at how to fix this in the next step.

image28

Step 19

After testing, you may realise that you need to change the font size for labels, label width/height, or placement of labels. You may also see overlapping text or items that appear to be in the wrong row. If you see this, you may need to adjust the row height. Click on the Table View (not the row) and then click on the Layout tab on the Properties panel. Under Table View Size, change the Row Height value to something more suitable and test your app. Keep adjusting the value and testing as needed. In this example app, the Row Height value has been changed to 115.

image29

That’s it! Now you can go and test your app! If you want to add a detail screen for each item in the list, then check out the next tutorial.

Passing data between screens on iOS with Xamarin

In this tutorial you will learn how to create an iOS 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 the same screen. Tapping a button will take the user to another screen that grabs information from the first screen and displays a fact. The app will look like this…

ipd1

Step 1

Open Xamarin and click File > New Solution to get started. Give your app a name (the app is called AnimalAgeCalculatorIOS in this example). Select a target iOS version and click Next.

ipd3

Step 2

Confirm the project and solution name as well as the project location. Click Create.

 

ipd4

Step 3

Open the Main.storyboard file in the Resources folder and drag a Label on to the screen. The label in this example app is given the Text value Enter your age in years.

ipd5

Then drag a Text Field element on to the screen with the placeholder text Age. Give this Text Field the Name ageTextField.

ipd6

Step 4

Add another label with the text value Convert to… and then four buttons with the following names:

  • dogButton
  • catButton
  • goatButton
  • hamsterButton

Then add another label with the text value Your result and a button with the text value Find out more and the Name detailsButton – as shown below.

ipd7

Step 5

Now open the ViewController.cs file and add a TouchUpInside+= event for the dogButton element inside the ViewDidLoad() method. As you type in the line dogButton.TouchUpInside+= and press the spacebar on your keyboard you will be presented with some options. Double-click on DogButton_TouchUpInside to create a new method of the same name. If you don’t see the option immediately, start typing it in until it shows up in the list and then double-click it to add the new method for the touch event.

ipd8

Step 6

Now repeat the last step for each of the buttons (adding a new method for the TouchUpInside events for each of the four animal buttons).

ipd9

Step 7

Add the following variables to the ViewController : UIViewController class:

  • float age; (stores the user’s age)
  • float animalAge; (stores the age of the user in selected animal years)
  • string animal; (stores the name of the animal the user selected)

ipd10

Step 8

Now add the following highlighted code in the methods for the button touch events. This will get the user’s age from the text field and store it in the age variable as a float value. The animal’s age will also be calculated (based on which animal button the user pressed) and stored in the animalAge variable as a float value. The selected animal’s name will be stored in the animal variable as a string value. The label displaying the result will also be updated.

ipd11

Step 9

Now drag a Navigation Controller from the toolbox onto the screen in the Main.storyboard file.

ipd12

Step 10

Right-click and delete the Root View Controller screen on the left (may have to do this twice).

ipd13

Step 11

Hold down the Control (Ctrl) key while clicking and dragging from the Navigation Controller screen (on the left) to the main screen (on the right). You’ll see a blue line appear connecting the two screens together and a menu will also appear.

ipd14

When the menu appears make sure you select Root.ipd14b

 

 

 

Step 12

Now drag a View Controller from the toolbox on to the screen and place it on the right side of the main screen. This will be the second screen in the app.

ipd15

Step 13

Drag a Label on to the screen. Give it a name and you will notice that a warning icon appears. Clicking on the warning icon will reveal the warning message.

ipd16

The warning message tells us that there is no codebehind for this screen so we will need to create one. This will create a second ViewController.cs file for this screen. Give it the name ResultViewController and press the Enter key.

ipd17

In the solution panel you should now see the ResultViewController.cs file in the list. This file is where we add the code for the second screen.

ipd18

Step 14

Now Control (Ctrl) click the Find out more button on the main screen and while holding down the mouse key, drag on to the second screen and release. A small menu will appear. Select Show (this means when the button is pressed, it will show the second screen).

ipd19

Step 15

Now go back to ViewController.cs and add a new method. Start typing public override PrepareForSegue and then double-click the method shown in the list to create it.

ipd21
Click the image for a larger version.

Add the following highlighted code to the new PrepareForSegue method. This will create a variable for the second screen/view controller and the two variables that will have their values passed to the second screen are also specified here.

ipd22
Click the image for a larger version.

Step 16

Now go to the ResultViewController.cs file (for the second screen) and add the following highlighted code in the ResultViewController : UIViewController class. This will declare the animalAge and animal variables with initial values of 0f for animalAge and an empty string for animal.

ipd23
Click the image for a larger version.

Step 17

Now drag a Text View element on to the second screen with the Name resultLabel and the Text value of Your result. Resize it so it has plenty of room for text.

ipd24

Step 18

Go back to the ResultViewController.cs file and add the ViewDidLoad method.

ipd25
Click the image for a larger version.

Inside the ViewDidLoad method, add the following highlighted code. This will display the result to the user based on their animal age and selected animal.

ipd26
Click the image for a larger version.

Step 19

Now drag a Button element from the toolbox on to the second screen in the Main.storyboard file and give it the Name value backButton and the Text value Back.

ipd27

Step 20

Now Control (Ctrl) click and drag from the Back button on the second screen to the main screen and click Show when the menu appears after releasing the mouse button. This will make the app take the user back to the main screen when they press the Back button.

ipd28

Step 21

The final step is to allow the user to dismiss the keyboard on the main screen when the keyboard is no longer required. Go back to the ViewController.cs file and add an override TouchesBegan method as shown below.

ipd29
Click the image for a larger version.

Inside the new override method, add the following highlighted line of code which will end editing and dismiss the keyboard when the user no longer requires it.

ipd30
Click the image for a larger version.

That’s it! Now go and save all your files and test your app.

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

Adding more screens to an iOS app

This tutorial explains how to add more than one screen to your iOS app and link screens together using buttons. We will use a simple example for this tutorial as show below…

iosmultiscreenapp

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

Video

Step 1

Start by creating a new solution (click File > New Solution).

ims1

Step 2

Give your app a name, select a minimum supported iOS version and click Next.

ims2a

Confirm the project and solution names, the project folder location and click Create.

ims2b

Step 3 

Open the Main.storyboard file and drag a Button element on to the screen. Give it a name and change its text value.

ims3

Step 4

Drag a Navigation Controller anywhere onto the storyboard. It should look like this…

ims4

Step 5

Right-click the Root View Controller and click Delete.

ims5

Step 6

Hold down the Ctrl (Control) key while dragging the Navigation Controller screen to your main screen (you will see a blue line linking the two screens together). The select Root from the list of options – this will make the main screen the root screen (the screen that loads first when the app starts running).

ims6

Step 7

Now drag a View Controller element onto the storyboard and place it to the right side of your main (root) screen. This will create a new screen which will be the second screen in your app.

ims7

Step 8

Hold down the Ctrl (Control) key while clicking and dragging the button on the main screen to the second screen. When you see the list of options appear, select Appear.

ims8

Step 9

Now we can add a Button to get from the second screen back to the main screen. Drag a button element on to the second screen. Give it a name. When you name the first element that you add to a new screen, you will see a yellow warning icon. Click it and then you will need to type in the name of the new ViewController for this screen  (for example, ScreenTwoViewController)– the name you provide will be the name of a new C# file that will contain the code for this screen. Change the Title property of the button the Back.

ims9

Step 10

Now click on the new button on the second screen. Hold down the Ctrl (Control) key while dragging this button to the main screen. Click on Show. This will make the Back button take the user back to the main screen when they tap it.

ims10

Lastly, double-click on the main screen’s title so you can rename it.

ims11

That’s it! Now you can test out your app.