Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Xamarin Blueprints
Xamarin Blueprints

Xamarin Blueprints: Leverage the power of Xamarin to create stunning cross-platform and native apps

Arrow left icon
Profile Icon Michael Williams
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (1 Ratings)
Paperback Sep 2016 516 pages 1st Edition
eBook
$42.99 $47.99
Paperback
$60.99
Subscription
Free Trial
Renews at $19.99p/m
Arrow left icon
Profile Icon Michael Williams
Arrow right icon
$19.99 per month
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (1 Ratings)
Paperback Sep 2016 516 pages 1st Edition
eBook
$42.99 $47.99
Paperback
$60.99
Subscription
Free Trial
Renews at $19.99p/m
eBook
$42.99 $47.99
Paperback
$60.99
Subscription
Free Trial
Renews at $19.99p/m

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing
Table of content icon View table of contents Preview book icon Preview Book

Xamarin Blueprints

Chapter 1.  Building a Gallery Application

This chapter will walkthrough native development with Xamarin by building an iOS and Android application that will read from your local gallery files, and display them in a UITableView and ListView. The following topics will be covered in this chapter:

Expected knowledge:

  • Creating iOS provision certificates
  • iOS development
  • Objective-C
  • Creating keystores
  • Android development
  • Java

In this chapter you will learn the following:

  • Creating an iOS project
  • Creating a UIViewController and UITableView
  • Customizing a cell's appearance
  • Creating an Android project
  • Creating an XML interface and ListView
  • Shared projects
  • Custom row appearance
  • Bitmap functions
  • The ALAssetLibrary
  • Adding the iOS photo screen
  • Adding the Android photo screen

Create an iOS project

Let's begin our Xamarin journey; we will start by setting up our iOS project in Xamarin Studio:

  1. Start by opening Xamarin Studio and creating a new iOS project. To do so, we simply select File | New | Solution and select an iOS Single View App; we must also give it a name and add the bundle ID you want in order to run your application.

    Note

    It is recommended that for each project, a new bundle ID is created, along with a developer provisioning profile for each project.

  2. Now that we have created the iOS project, you will be taken to the following screen:
Create an iOS project

Doesn't this look familiar? Yes, it is our AppDelegate file; notice the .cs on the end; because we are using C#, all our code files will have this extension (no more .h or .m files).

Tip

Before we go any further, spend a few minutes moving around the IDE, expanding the folders, and exploring the project structure; it is very similar to an iOS project created in XCode.

Creating a UIViewController and UITableView

Now that we have our new iOS project, we are going to start by creating a UIViewController. Right-click on the project file, select Add | New File, and select ViewController from the iOS menu selection in the left-hand box:

Creating a UIViewController and UITableView

You will notice three files generated, a .xib, a .cs, and a .designer.cs file. We don't need to worry about the third file; this is automatically generated based upon the other two files.

Tip

Right-click on the project item and select Reveal in Finder,

Creating a UIViewController and UITableView

This will bring up the finder where you will double-click on the GalleryCell.xib file; this will bring up the user interface designer in XCode. You should see automated text inserted into the document to help you get started.

Firstly, we must set our namespace accordingly, and import our libraries with using statements. In order to use the iOS user interface elements, we must import the UIKit and CoreGraphics libraries. Our class will inherit the UIViewController class in which we will override the ViewDidLoad function:

namespace Gallery.iOS  
{ 
    using System; 
    using System.Collections.Generic; 
 
    using CoreGraphics; 
    using UIKit; 
 
    public partial class MainController : UIViewController 
    { 
        private UITableView _tableView; 
 
        private TableSource _source; 
 
        private ImageHandler _imageHandler; 
 
        public MainController () : base ("MainController", null) 
        { 
            _source = new TableSource (); 
 
            _imageHandler = new ImageHandler (); 
            _imageHandler.AssetsLoaded += handleAssetsLoaded; 
        } 
 
        private void handleAssetsLoaded (object sender, EventArgs e) 
        { 
            _source.UpdateGalleryItems (_imageHandler.CreateGalleryItems()); 
            _tableView.ReloadData (); 
        } 
 
        public override void ViewDidLoad () 
        { 
            base.ViewDidLoad (); 
 
            var width = View.Bounds.Width; 
            var height = View.Bounds.Height; 
 
            tableView = new UITableView(new CGRect(0, 0, width, height)); 
            tableView.AutoresizingMask = UIViewAutoresizing.All; 
            tableView.Source = _source; 
 
            Add (_tableView); 
        } 
    } 
} 

Our first UI element created is UITableView. This will be used to insert into the UIView of the UIViewController, and we also retrieve width and height values of the UIView to stretch the UITableView to fit the entire bounds of the UIViewController. We must also call Add to insert the UITableView into the UIView. In order to fill the list with data, we need to create a UITableSource to contain the list of items to be displayed in the list. We will also need an object called GalleryModel; this will be the model of data to be displayed in each cell.

Follow the previous process for adding two new .cs files; one will be used to create our UITableSource class and the other for the GalleryModel class. In TableSource.cs, first we must import the Foundation library with the using statement:

using Foundation; 

Now for the rest of our class. Remember, we have to override specific functions for our UITableSource to describe its behavior. It must also include a list for containing the item view-models that will be used for the data displayed in each cell:

public class TableSource : UITableViewSource  
    { 
        protected List<GalleryItem> galleryItems; 
        protected string cellIdentifier = "GalleryCell"; 
 
        public TableSource (string[] items) 
        { 
            galleryItems = new List<GalleryItem> (); 
        } 
    } 

We must override the NumberOfSections function; in our case, it will always be one because we are not having list sections:

        public override nint NumberOfSections (UITableView tableView) 
        { 
            return 1; 
        } 

To determine the number of list items, we return the count of the list:

        public override nint RowsInSection (UITableView tableview, nint section) 
        { 
            return galleryItems.Count; 
        } 

Then we must add the GetCell function; this will be used to get the UITableViewCell to render for a particular row. But before we do this, we need to create a custom UITableViewCell.

Customizing a cell's appearance

We are now going to design our cells that will appear for every model found in the TableSource class. Add a new .cs file for our custom UITableViewCell.

Note

We are not going to use a .xib and simply build the user interface directly in code using a single .cs file.

Now for the implementation:

public class GalleryCell: UITableViewCell   
    { 
        private UIImageView _imageView; 
 
        private UILabel _titleLabel; 
 
        private UILabel _dateLabel; 
 
        public GalleryCell (string cellId) : base (UITableViewCellStyle.Default, cellId) 
        { 
            SelectionStyle = UITableViewCellSelectionStyle.Gray; 
 
            _imageView = new UIImageView() 
            { 
                TranslatesAutoresizingMaskIntoConstraints = false, 
            }; 
 
            _titleLabel = new UILabel ()  
            { 
                TranslatesAutoresizingMaskIntoConstraints = false, 
            }; 
 
            _dateLabel = new UILabel ()  
            { 
                TranslatesAutoresizingMaskIntoConstraints = false, 
            }; 
 
            ContentView.Add (imageView); 
            ContentView.Add (titleLabel); 
            ContentView.Add (dateLabel); 
        } 
    } 

Our constructor must call the base constructor, as we need to initialize each cell with a cell style and cell identifier. We then add a UIImageView and two UILabels for each cell, one for the filename and one for the date. Finally, we add all three elements to the main content view of the cell.

When we have our initializer, we add the following:

public void UpdateCell (GalleryItem gallery) 
        { 
            _imageView.Image = UIImage.LoadFromData (NSData.FromArray (gallery.ImageData)); 
            _titleLabel.Text = gallery.Title; 
            _dateLabel.Text = gallery.Date; 
        } 
 
        public override void LayoutSubviews () 
        { 
            base.LayoutSubviews (); 
 
            ContentView.TranslatesAutoresizingMaskIntoConstraints = false; 
 
            // set layout constraints for main view 
            AddConstraints (NSLayoutConstraint.FromVisualFormat("V:|[imageView(100)]|", NSLayoutFormatOptions.DirectionLeftToRight, null, new NSDictionary("imageView", imageView))); 
            AddConstraints (NSLayoutConstraint.FromVisualFormat("V:|[titleLabel]|", NSLayoutFormatOptions.DirectionLeftToRight, null, new NSDictionary("titleLabel", titleLabel))); 
            AddConstraints (NSLayoutConstraint.FromVisualFormat("H:|-10-[imageView(100)]-10-[titleLabel]-10-|", NSLayoutFormatOptions.AlignAllTop, null, new NSDictionary ("imageView", imageView, "titleLabel", titleLabel))); 
            AddConstraints (NSLayoutConstraint.FromVisualFormat("H:|-10-[imageView(100)]-10-[dateLabel]-10-|", NSLayoutFormatOptions.AlignAllTop, null, new NSDictionary ("imageView", imageView, "dateLabel", dateLabel))); 
        } 

Our first function, UpdateCell, simply adds the model data to the view, and our second function overrides the LayoutSubViews method of the UITableViewCell class (equivalent to the ViewDidLoad function of a UIViewController).

Now that we have our cell design, let's create the properties required for the view-model. We only want to store data in our GalleryItem model, meaning we want to store images as byte arrays. Let's create a property for the item model:

namespace Gallery.iOS 
{ 
    using System; 
 
    public class GalleryItem 
    { 
        public byte[] ImageData; 
 
        public string ImageUri; 
 
        public string Title; 
 
        public string Date; 
 
        public GalleryItem () 
        { 
        } 
    } 
} 

Now back to our TableSource class. The next step is to implement the GetCell function:

public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath) 
        { 
            var cell = (GalleryCell)tableView.DequeueReusableCell (CellIdentifier); 
            var galleryItem = galleryItems[indexPath.Row]; 
 
            if (cell == null) 
            {  
                // we create a new cell if this row has not been created yet 
                cell = new GalleryCell (CellIdentifier);  
            } 
 
            cell.UpdateCell (galleryItem); 
 
            return cell; 
        } 

Notice the cell reuse on the if statement; you should be familiar with this type of approach, it is a common pattern for reusing cell views and is the same as the Objective-C implementation (this is a very basic cell reuse implementation). We also call the UpdateCell method to pass in the required GalleryItem data to show in the cell. Let's also set a constant height for all cells. Add the following to your TableSource class:

public override nfloat GetHeightForRow (UITableView tableView, NSIndexPath indexPath) 
        { 
            return 100; 
        } 

So what is next?

public override void ViewDidLoad () 
{ 
.. 
table.Source = new TableSource(); 
.. 
} 

Let's stop development and have a look at what we have achieved so far. We have created our first UIViewController, UITableView, UITableViewSource, and UITableViewCell, and bound them all together. Fantastic!

We now need to access the local storage of the phone to pull out the required gallery items. But before we do this, we are going to create an Android project and replicate what we have done with iOS.

Creating an Android project

Our first step is to create new general Android app:

Creating an Android project

The first screen you will land on is MainActivity. This is our starting activity, which will inflate the first user interface; take notice of the configuration attributes:

[Activity (Label = "Gallery.Droid", MainLauncher = true, Icon = "@mipmap/icon")] 

The MainLauncher flag indicates the starting activity; one activity must have this flag set to true so the application knows what activity to load first. The icon property is used to set the application icon, and the Label property is used to set the text of the application, which appears in the top left of the navigation bar:

namespace Gallery.Droid 
{ 
    using Android.App; 
    using Android.Widget; 
    using Android.OS; 
 
    [Activity (Label = "Gallery.Droid", MainLauncher = true, Icon = "@mipmap/icon")] 
    public class MainActivity : Activity 
    { 
        int count = 1; 
 
        protected override void OnCreate (Bundle savedInstanceState) 
        { 
            base.OnCreate (savedInstanceState); 
 
            // Set our view from the "main" layout resource 
            SetContentView (Resource.Layout.Main); 
        } 
    } 
} 

The formula for our activities is the same as Java; we must override the OnCreate method for each activity where we will inflate the first XML interface Main.xml.

Creating an XML interface and ListView

Our starting point is the main.xml sheet; this is where we will be creating the ListView:

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"> 
    <ListView 
        android:id="@+id/listView" 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" 
        android:layout_marginBottom="10dp" 
        android:layout_marginTop="5dp" 
        android:background="@android:color/transparent" 
        android:cacheColorHint="@android:color/transparent" 
        android:divider="#CCCCCC" 
        android:dividerHeight="1dp" 
        android:paddingLeft="2dp" /> 
</LinearLayout> 

Tip

The main.xml file should already be in the resource | layout directory, so simply copy and paste the previous code into this file.

Excellent! We now have our starting activity and interface, so now we have to create a ListAdapter for our ListView. An adapter works very much like a UITableSource, where we must override functions to determine cell data, row design, and the number of items in the list.

Note

Xamarin Studio also has an Android GUI designer.

Right-click on the Android project and add a new empty class file for our adapter class. Our class must inherit the BaseAdapter class, and we are going to override the following functions:

public override long GetItemId(int position); 
 
public override View GetView(int position, View convertView, ViewGroup parent); 

Before we go any further, we need to create a model for the objects used to contain the data to be presented in each row. In our iOS project, we created a GalleryItem to hold the byte array of image data used to create each UIImage. We have two approaches here: we could create another object to do the same as the GalleryItem, or even better, why don't we reuse this object using a shared project?

Left arrow icon Right arrow icon
Download code icon Download Code

Key benefits

  • Helps you get a clear practical understanding of creating professional-grade apps with Xamarin
  • Covers Xamarin.Forms, Xamarin Android, and Xamarin iOS
  • If you want to transform yourself from an amateur mobile developer into a professional app developer across multiple platforms, then this is the ideal book for you

Description

Do you want to create powerful, efficient, and independent apps from scratch that will leverage the Xamarin framework and code with C#? Well, look no further; you’ve come to the right place! This is a learn-as-you-build practical guide to building eight full-fledged applications using Xamarin.Forms, Xamarin Android, and Xamarin iOS. Each chapter includes a project, takes you through the process of building applications (such as a gallery Application, a text-to-speech service app, a GPS locator app, and a stock market app), and will show you how to deploy the application’s source code to a Google Cloud Source Repository. Other practical projects include a chat and a media-editing app, as well as other examples fit to adorn any developer’s utility belt. In the course of building applications, this book will teach you how to design and prototype professional-grade applications implementing performance and security considerations.

Who is this book for?

If you are a mobile developer looking to create interesting and fully featured apps for different platforms, then this book is the ideal solution for you. A basic knowledge of Xamarin and C# programming is assumed

What you will learn

  • Discover eight different ways to create your own Xamarin applications
  • Improve app performance by using SQLite for data-intensive applications
  • Set up a simple web service to feed JSON data into mobile applications
  • Store files locally with Xamarin.Forms using dependency services
  • Use Xamarin extension libraries to create effective applications with less coding

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Sep 30, 2016
Length: 516 pages
Edition : 1st
Language : English
ISBN-13 : 9781785887444
Vendor :
Microsoft
Category :
Languages :

What do you get with a Packt Subscription?

Free for first 7 days. $19.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details

Publication date : Sep 30, 2016
Length: 516 pages
Edition : 1st
Language : English
ISBN-13 : 9781785887444
Vendor :
Microsoft
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total $74.98 $83.98 $9.00 saved
Xamarin Blueprints
$60.99
Xamarin Cross-Platform Development Cookbook
$99.99
Total $74.98$83.98 $9.00 saved Stars icon

Table of Contents

8 Chapters
1. Building a Gallery Application Chevron down icon Chevron up icon
2. Building a SpeechTalk Application Chevron down icon Chevron up icon
3. Building a GPS Locator Application Chevron down icon Chevron up icon
4. Building an Audio Player Application Chevron down icon Chevron up icon
5. Building a Stocklist Application Chevron down icon Chevron up icon
6. Building a Chat Application Chevron down icon Chevron up icon
7. Building a File Storage Application Chevron down icon Chevron up icon
8. Building a Camera Application Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(1 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Xavier Minaya Ruiz May 16, 2017
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very good book. It combines Xamarin.Forms and native coding patterns. Recommended.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.