Xamarin Blueprints
()
About this ebook
- 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
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.
Michael Williams
Michael Williams (PhD, University of Pennsylvania) is Emeritus Senior Professor of Old Testament Studies at Calvin Theological Seminary, a member of the NIV Committee on Bible Translation and the Chairman of the NIrV Committee. He is the author of Deception in Genesis, The Prophet and His Message, Basics of Ancient Ugaritic, The Biblical Hebrew Companion for Bible Software Users, How to Read the Bible through the Jesus Lens, Hidden Prophets of the Bible and is editor and contributor of Mishneh Todah. His passion is to provide curious believers with knowledge of the Old Testament and its culture so that they may grow in their comprehension and appreciation of redemptive history and be adequately prepared to promote and defend the faith through word and action. Michael resides in Florida with his wife, Dawn.
Read more from Michael Williams
How to Read the Bible through the Jesus Lens: A Guide to Christ-Focused Reading of Scripture Rating: 4 out of 5 stars4/5Groundless Belief: An Essay on the Possibility of Epistemology - Second Edition Rating: 0 out of 5 stars0 ratingsWereWolf Rating: 0 out of 5 stars0 ratingsHidden Prophets of the Bible: Finding the Gospel in Hosea through Malachi Rating: 0 out of 5 stars0 ratingsFarm Tractors: A Complete Illustrated History Rating: 0 out of 5 stars0 ratings30 Old Testament Passages with Deeper Meaning: The Surprising Significance of Seemingly Ordinary Verses Rating: 0 out of 5 stars0 ratingsThe Day I Spent In Heaven Rating: 5 out of 5 stars5/5Superman Could Fly Rating: 0 out of 5 stars0 ratingsDeforesting the Earth: From Prehistory to Global Crisis, An Abridgment Rating: 4 out of 5 stars4/5Europa Exploration Mission Rating: 0 out of 5 stars0 ratingsEastern Sevier County Rating: 0 out of 5 stars0 ratingsThe Long Road to Blessed: Keep Putting One Foot in Front of the Other Rating: 0 out of 5 stars0 ratingsHaunted North Cornwall Rating: 2 out of 5 stars2/5The Little Ones Rating: 0 out of 5 stars0 ratingsTo Pass On a Good Earth: The Life and Work of Carl O. Sauer Rating: 4 out of 5 stars4/5By the Pleasing Countenance of My Superiors Rating: 0 out of 5 stars0 ratingsFarm Tractors: A Complete Illustrated History Rating: 0 out of 5 stars0 ratingsElementary Concerns Rating: 0 out of 5 stars0 ratingsKathy's Birthday Wish Rating: 0 out of 5 stars0 ratingsPlexus Rating: 0 out of 5 stars0 ratingsTo God Be The Glory For The Things He Has Done And Will Do Part II Rating: 0 out of 5 stars0 ratingsTo God Be The Glory For The Things He Has Done And Will Do! Rating: 0 out of 5 stars0 ratingsThe Brown Crayon Rating: 0 out of 5 stars0 ratingsThe Boys of Milo Rating: 0 out of 5 stars0 ratingsThe Love from Just One Rating: 0 out of 5 stars0 ratingsPatrick Rating: 0 out of 5 stars0 ratings
Related to Xamarin Blueprints
Related ebooks
Mastering Visual Studio: A Comprehensive Guide Rating: 0 out of 5 stars0 ratingsBlazor WebAssembly by Example: A project-based guide to building web apps with .NET, Blazor WebAssembly, and C# Rating: 0 out of 5 stars0 ratingsXamarin Mobile Application Development for Android - Second Edition Rating: 0 out of 5 stars0 ratingsASP.NET 2.0 Web Parts in Action: Building Dynamic Web Portals Rating: 0 out of 5 stars0 ratingsJava Complete Self-Assessment Guide Rating: 0 out of 5 stars0 ratingsjQuery Mobile Web Development Essentials - Third Edition Rating: 0 out of 5 stars0 ratingsDeveloping Windows Store Apps with HTML5 and JavaScript Rating: 0 out of 5 stars0 ratingsBeginning DotNetNuke Skinning and Design Rating: 0 out of 5 stars0 ratingsApplication Support A Complete Guide - 2019 Edition Rating: 0 out of 5 stars0 ratingsContinuous Integration in .NET Rating: 0 out of 5 stars0 ratingsMastering JBoss Drools 6 Rating: 0 out of 5 stars0 ratingsUltimate Node.js for Cross-Platform App Development Rating: 0 out of 5 stars0 ratingsExt JS in Action Rating: 0 out of 5 stars0 ratingsMVVM Survival Guide for Enterprise Architectures in Silverlight and WPF Rating: 0 out of 5 stars0 ratingsProfessional Visual Studio 2017 Rating: 0 out of 5 stars0 ratingsSharePoint 2010 Web Parts in Action Rating: 0 out of 5 stars0 ratingsBuilding iOS 17 Apps with Xcode Storyboards: Develop iOS 17 Apps with Xcode 15 and Swift Rating: 0 out of 5 stars0 ratingsJava Platform Enterprise Edition Java EE Complete Self-Assessment Guide Rating: 0 out of 5 stars0 ratingsSwiftUI Cookbook: A guide for building beautiful and interactive SwiftUI apps Rating: 0 out of 5 stars0 ratingsBeginning Visual Basic 2015 Rating: 5 out of 5 stars5/5Microsoft Dynamics NAV Administration Rating: 0 out of 5 stars0 ratingsGetting Started with OpenCart Module Development Rating: 0 out of 5 stars0 ratingsApps and Services with .NET 8: Build practical projects with Blazor, .NET MAUI, gRPC, GraphQL, and other enterprise technologies Rating: 0 out of 5 stars0 ratingsData Engineering with Python: Work with massive datasets to design data models and automate data pipelines using Python Rating: 0 out of 5 stars0 ratingsMastering ASP.NET Web API Rating: 0 out of 5 stars0 ratingsPowerBuilder A Complete Guide - 2019 Edition Rating: 0 out of 5 stars0 ratingsMore Advanced CSS: Zombie in a Ballgown: Undead Institute Rating: 0 out of 5 stars0 ratingsNosql A Complete Guide - 2019 Edition Rating: 0 out of 5 stars0 ratings
Programming For You
Coding All-in-One For Dummies Rating: 4 out of 5 stars4/5Grokking Algorithms: An illustrated guide for programmers and other curious people Rating: 4 out of 5 stars4/5Python Programming : How to Code Python Fast In Just 24 Hours With 7 Simple Steps Rating: 4 out of 5 stars4/5Excel : The Ultimate Comprehensive Step-By-Step Guide to the Basics of Excel Programming: 1 Rating: 5 out of 5 stars5/5SQL QuickStart Guide: The Simplified Beginner's Guide to Managing, Analyzing, and Manipulating Data With SQL Rating: 4 out of 5 stars4/5Python Machine Learning By Example Rating: 4 out of 5 stars4/5Excel 101: A Beginner's & Intermediate's Guide for Mastering the Quintessence of Microsoft Excel (2010-2019 & 365) in no time! Rating: 0 out of 5 stars0 ratingsLinux: Learn in 24 Hours Rating: 5 out of 5 stars5/5Learn to Code. Get a Job. The Ultimate Guide to Learning and Getting Hired as a Developer. Rating: 5 out of 5 stars5/5Python QuickStart Guide: The Simplified Beginner's Guide to Python Programming Using Hands-On Projects and Real-World Applications Rating: 0 out of 5 stars0 ratingsHTML & CSS: Learn the Fundaments in 7 Days Rating: 4 out of 5 stars4/5JavaScript All-in-One For Dummies Rating: 5 out of 5 stars5/5Python: For Beginners A Crash Course Guide To Learn Python in 1 Week Rating: 4 out of 5 stars4/5Python: Learn Python in 24 Hours Rating: 4 out of 5 stars4/5Learn PowerShell in a Month of Lunches, Fourth Edition: Covers Windows, Linux, and macOS Rating: 5 out of 5 stars5/5Microsoft Azure For Dummies Rating: 0 out of 5 stars0 ratingsPYTHON: Practical Python Programming For Beginners & Experts With Hands-on Project Rating: 5 out of 5 stars5/5Unreal Engine from Zero to Proficiency (Foundations): Unreal Engine from Zero to Proficiency, #1 Rating: 3 out of 5 stars3/5C++ Learn in 24 Hours Rating: 0 out of 5 stars0 ratingsC# Programming from Zero to Proficiency (Beginner): C# from Zero to Proficiency, #2 Rating: 0 out of 5 stars0 ratings
Reviews for Xamarin Blueprints
0 ratings0 reviews
Book preview
Xamarin Blueprints - Michael Williams
Table of Contents
Xamarin Blueprints
Credits
About the Author
About the Reviewer
www.PacktPub.com
Why subscribe?
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Errata
Piracy
Questions
1. Building a Gallery Application
Create 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
Summary
2. Building a SpeechTalk Application
Cross-platform development with Xamarin.Forms
So how would this look in Xamarin.Forms?
Setting up platform projects
So what is happening here?
Setting up the SpeechTalk.iOS project
Setting up the SpeechTalk.Droid project
Xamarin.Forms, Windows Phone, and Visual Studio
What can we see here?
Inversion of Control (IoC) with Xamarin.Forms
So why should we use it?
So how do we benefit from this?
Autofac
iOS text-to-speech implementation
Bindings
Android text-to-speech implementation
Setting up IoC with Android
WinPhone text-to-speech implementation
IoC with Windows Phone
Platform independent styling
Summary
3. Building a GPS Locator Application
Core location and GPS
Project setup
Navigation with Xamarin.Forms
Why would we do this?
Building the navigation control
View model navigation
Integrating Google Maps using Xamarin.Forms.Maps
Reactive Extensions
Core location with iOS and the CLLocationManager library
Handling location updates
Android and the LocationManager
Creating an exit point
Creating an API key for Android
Creating our Windows project
Core Location Services with Windows Phone
The Application class
Web services and data contracts
What about data contracts?
Creating another API key for geocoding
Creating GeocodingWebServiceController
Newtonsoft.Json and Microsoft HTTP client libraries
ModernHttpClient and client message handlers
Feeding JSON data into the IObservable framework
More Reactive Extensions
Resource (RESX) files
Using GeocodingWebServiceController
OnNavigatedTo and OnShow
Pythagoras equirectangular projection
How are we going to calculate the closest position?
Summary
4. Building an Audio Player Application
Solution setup
Inversion of control with MVVMCross
View-models with Xamarin native
Creating the bindings
NSLayoutContraints
MVVMCross setup inside the PCL
Setting up MVVMCross with iOS
Setting up MVVMCross with Android
The SoundHandler interface
Implementing the iOS SoundHandler using the AVAudioPlayer framework
The Mvx IoC container
The audio player
A cleaner code approach to NSLayout
Creating AudioPlayerPageViewModel
Implementing the Android SoundHandler using the MediaPlayer framework
XML and Mvx bindings
MvxActivities
Summary
5. Building a Stocklist Application
Understanding the backend
Creating an ASP.Net Web API 2 project
Building an API controller
Setting up the mobile projects
Building core mobile projects
Improving app performance
Creating a global App.xaml
Theming with ControlTemplates
Updating the MainPageViewModel
Creating the Stocklist web service controller
ListViews and ObservableCollections
Value converters
Adding a DataTemplate to the global resource dictionary
Styles
Further optimization with XAML
Creating StockItemDetailsPage
Custom renderers
Adding styles for custom elements
Creating StockItemDetailsPageViewModel
Setting up the native platform projects
Hosting the Web API project locally
Summary
6. Building a Chat Application
The Model-View-Presenter (MVP) pattern
So why bother with this approach?
Architecture
How do we determine which layers our project needs?
SignalR
Starting with Open Web Interface for .NET (OWIN)
Creating an authorization server using OWIN OAuth 2.0
OAuthAuthorizationServerProvider
Use OAuthBearerAuthentication
Setting up the AuthenticationRepository
Configuring the Web API
Building the AccountController
Configuring OAuth Authentication with our Web API
Building the SignalR Hub
Setting up mobile projects
Creating the SignalRClient
Building the WebApiAccess layer
Application state
Setting up the navigation service
Building the iOS navigation service
Building the Android navigation service
Building the iOS interface
Handling Hub proxy callbacks
Implementing the LoginPresenter
Creating the connection between Presenter and View
Building the LoginActivity
Implementing the ClientsListPresenter
Creating ClientListViewController
The TaskCompletionSource framework
Creating the ClientsListActivity
Overriding the OnBackPressed activity
Building the ListAdapter
Building the ChatPresenter
Building the iOS ChatView
Extending the UIColor framework
Android TableLayouts
Building the Android ChatActivity
Running the server and clients
Summary
7. Building a File Storage Application
Project structure setup
Building a data access layer using SQLite
Building the ISQLiteStorage interface
Adding additional threading techniques
How do we solve this problem?
Creating the AsyncSemaphore
Creating the AsyncLock
Implementing native setup requirements for SQLite
Implementing the IoC container and modules
Implementing cross-platform logging
Implementing the SQLiteStorage class
Introduction to C# 6.0 syntax
Handling alerts in view-models
Building the IMethods interface
Building the ExtendedContentPage
Why are we implementing two different techniques for showing alerts?
Building a CarouselView using custom layouts
Adding scroll control to the CarouselView
Building a CustomRenderer for native gestures
Building the user interface
Using a SynchronizationContext
How do we know this context is from the main UI thread?
Building the EditFilePage
Behaviours
Challenge
Building the Windows Phone version
Summary
8. Building a Camera Application
Solution setup
Building the MainPageViewModel class
Improving the INotifiedPropertyChanged implementation
Creating the custom UI objects
Building the FocusView
Xamarin.Forms animations
Xamarin.Forms compound animations
Building the CameraView
Building a control for the iOS camera
Building the iOS CameraRenderer
Integrating the Android Camera2 framework
Building the CameraViewRenderer in Android
Handling native touch events through the FocusView
Using RX to handle events
Building a VisualElementRenderer for iOS
Building the CustomImageRenderers
Building the UIImageEffects class
Building the CustomImageRenderer for Android
Triggers
Easing.SinIn
Easing.SinOut
Platform effects
Building the CameraPage
Adding native orientation events
Challenge
Summary
Xamarin Blueprints
Xamarin Blueprints
Copyright © 2016 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: September 2016
Production reference: 1270916
Published by Packt Publishing Ltd.
Livery Place
35 Livery Street
Birmingham
B3 2PB, UK.
ISBN 978-1-78588-744-4
www.packtpub.com
Credits
About the Author
Michael Williams is an Insightful, results-driven full stack developer with notable experience in cross-platform development using Xamarin and native languages for multiple platforms. He also builds and researches server-side architecture using CQRS and event-sourcing. He shares his knowledge on his personal blog at (www.imobservable.com).
Also an entrepreneur, the owner of Flush Arcade, a company involved in developing creative, innovative, and ideative games (www.flusharcade.com).
About the Reviewer
Engin Polat has been involved in many large and medium-scale projects on .NET technologies as a developer, architect, and consulting and has won many awards since 1999.
Since 2008, he has been giving training to many large enterprises in Turkey about Windows development, Web development, distributed application development, software architecture, mobile development, cloud development, and so on. Apart from this, he organizes seminars and events in many universities in Turkey about .NET technologies, Windows platform development, cloud development, Web development, game development, and so on.
He shares his experiences on his personal blog (http://www.enginpolat.com). He has MCP, MCAD, MCSD, MCDBA, and MCT certifications.
Since 2012 he has been recognized as a Windows Platform Development MVP (Most Valuable Professional) by Microsoft. Between 2013 and 2015, he was recognized as a Nokia Developer Champion; very few people in the world are given this award.
Since 2015 he also recognized as a Microsoft Regional Director by Microsoft.
www.PacktPub.com
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www2.packtpub.com/books/subscription/packtlib
Do you need instant solutions to your IT questions? PacktLib is Packt's online digital book library. Here, you can search, access, and read Packt's entire library of books.
Why subscribe?
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Preface
Throughout my journey as a mobile developer, I have worked with many different development paradigms and techniques. I have built mobile applications in Java, objective-C, Swift (2 and 3), and C# across all mobile platforms. I’ve even built entire servers for my mobile applications.
I'm not standing here to brag, or to say that I'm an expert. But I do believe that I have encountered a ton of problems, and built solutions that a lot of mobile developers will require.
My latest work has been around building cross-platform solutions with Xamarin using both native and Xamarin.Forms. I have spent a lot of time narrowing down, what I believe are the best approaches in building any cross-platform mobile application. Building good architecture, structure, and a smooth user experience, whilst sharing as much code as possible.
Enjoy.
What this book covers
Chapter 1, Building a Gallery Application, provides you a walkthrough for native development with Xamarin by building an iOS and Android application that will read from your local gallery files and display them into a UITableView and ListView.
Chapter 2, Build a SpeechTalk Application, provides you a walkthrough of Xamarin.Forms development by building an iOS, Android and Windows Phone application that will use platform speech services to talk text typed into a text field.
Chapter 3, Building a GPS Locator Application, shows you how to build a Xamarin.Forms application that integrates native GPS location services and Google Maps APIs. We will cover more content on IoC containers, the Xamarin.Forms.Maps library, and techniques for C# async and background tasks.
Chapter 4, Building an Audio Player Application, in this chapter, we will integrate native audio functions for processing a sound file using the AVFramework in iOS, and MediaPlayer framework in Android.
Chapter 5, Building a Stocklist Application, in this chapter we look at detailing our XAML interfaces using CustomRenderers, Styles, and ControlTemplates. We also build a simple web service and setup a JSON feed for our mobile application.
Chapter 6, Building a Chat Application, in this chapter our user interface will move away from MVVM design and follow a new paradigm called MVP (Model-View-Presenter). We take another step further into the backend and set up a SignalR hub and client to simulate a chat service, where data will be sent between the server and clients instantly as the messages become available. Another key topic of focus is the project architecture, spending time on separating the project into modules, and creating a nicely tiered structure that will maximize code sharing across different platforms.
Chapter 7, Building a File Storage Application, in this chapter we walk through more development using Xamarin.Forms. We look at Behaviors and their use with user interfaces. We also build a custom layout using the Layout
Chapter 8, Building a Camera Application, our last chapter, will introduce Effects and Triggers. We learn how to apply them to user interfaces and use them with Styles. We also build multiple complex CustomRenderers for native platform cameras, tinting images and receiving touch events.
What you need for this book
Xamarin Studio
To install a copy of Xamarin Studio visit the following link:
https://www.xamarin.com/download
Building Windows Phone Applications
In order to build windows phone applications, you will need a computer with Windows, Microsoft Visual Studio, and the Universal Windows Platform SDK installed.
Running solutions
You will also need an iOS, android and windows phone device for testing. If you don’t have access to devices, you will have to install simulators for each platform.
iOS
Simulators can be installed via XCode. If you haven’t got XCode installed, you will need to install a fresh copy.
Android
Please install a copy of Geny Motion from the link below:
https://www.genymotion.com/
Windows Phone
The UWP SDK comes with simulators for Microsoft Visual Studio.
Who this book is 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.
Conventions
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning.
Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: Yes, it is our AppDelegate file; notice the .cs on the end.
A block of code is set as follows:
private void handleAssetsLoaded (object sender, EventArgs e)
{
_source.UpdateGalleryItems (_imageHandler.CreateGalleryItems());
_tableView.ReloadData ();
}
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: To do so, we simply select File | New | Solution and select an iOS Single View App.
Note
Warnings or important notes appear in a box like this.
Tip
Tips and tricks appear like this.
Reader feedback
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Customer support
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
Downloading the example code
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.
You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the SUPPORT tab at the top.
Click on Code Downloads & Errata.
Enter the name of the book in the Search box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on Code Download.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Xamarin-Blueprints. We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Errata
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title.
To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy.
Please contact us at [email protected] with a link to the suspected pirated material.
We appreciate your help in protecting our authors and our ability to bring you valuable content.
Questions
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
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:
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.
Now that we have created the iOS project, you will be taken to the following screen:
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:
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,
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
protected string cellIdentifier = GalleryCell
;
public TableSource (string[] items)
{
galleryItems = new List
}
}
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:
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:
1.0 encoding=utf-8
?>
android:orientation=vertical
android:layout_width=fill_parent
android:layout_height=fill_parent
>
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
/>
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?
Shared projects
We are going to delve into our first technique for sharing code between different platforms. This is what Xamarin wants us to achieve, and reuse as much code as possible. The biggest disadvantage when developing natively is two different language, and we can't reuse anything.
Let's create our first shared project:
Our shared project will be used to contain the GalleryItem model, so whatever code we include in this shared project can be accessed by both the iOS and Android projects:
In the preceding screenshot, have a look at the Solution explorer, and notice how the shared project doesn't contain anything more than .cs code sheets. Shared projects do not have any references or components, just code that is shared by all platform projects. When our native projects reference these shared projects, any libraries being referenced via using statements come from the native projects.
Now we must have the iOS and Android projects reference the shared project; right-click on the References folder and select Edit References:
Select the shared project you just created and we can now reference the GalleryItem object from both projects.
Custom row appearance
Let's get back to the ListAdapter implementation and design our ListView row appearance. Open the Resources | Layout folder, create a new .xml file for the cell appearance, call it CustomCell.xml, and copy in the following XML code:
1.0 encoding=utf-8
?>
android:orientation=horizontal
android:layout_width=match_parent
android:layout_height=match_parent
android:weightSum=4
>
android:orientation=vertical
android:layout_width=match_parent
android:layout_height=match_parent
android:layout_weight=1
>
android:id=@+id/image
android:layout_width=100dp
android:layout_height=100dp
android:adjustViewBounds=true
/>
android:orientation=vertical
android:layout_width=match_parent
android:layout_height=match_parent
android:layout_weight=3
android:weightSum=2
>
android:id=@+id/title
android:layout_width=wrap_content
android:layout_height=wrap_content
android:layout_weight=1
/>
android:id=@+id/date
android:layout_width=wrap_content
android:layout_height=wrap_content
android:layout_weight=1
/>
We are creating the same layout as the custom cell made for iOS, but in Android we will use the ImageView and TextView objects. Now that we have our custom cell, we can implement the the GetView function. The GetView function is exactly like the GetCell function in the preceding UITableSource implementation. Open up the ListAdapter.cs file and continue with the list adapter implementation:
public class ListAdapter : BaseAdapter
{
private List
private Activity _context;
public ListAdapter(Activity context) : base()
{
_context = context;
_items = new List
}
public override Java.Lang.Object GetItem (int position)
{
return null;
}
public override long GetItemId(int position)
{
return position;
}
public override int Count
{
get
{
return items.Count;
}
}
}
We override the Count property and functions GetItemId and GetItem, to return the number of gallery items in our list. These override functions are exactly the same as the overrides in Java for any BaseAdapter inherited class. Now for the GetView function:
public override View GetView(int position, View convertView, ViewGroup parent)
{
View view = convertView; // re-use an existing view, if one is available
if (view == null)
{
// otherwise create a new one
view = context.LayoutInflater.Inflate(Resource.Layout.CustomCell, null);
}
// set image
var imageView = view.FindViewById
BitmapHelpers.CreateBitmap (imageView, _items [position].ImageData);
// set labels
var titleTextView = view.FindViewById
titleTextView.Text = _items[position].Title;
var dateTextView = view.FindViewById
dateTextView.Text = _items[position].Date;
return view;
}
private async void createBitmap(ImageView imageView, byte[] imageData)
{
try
{
if (imageData != null)
{
var bm = await BitmapFactory.DecodeByteArrayAsync(imageData, 0, imageData.Length);
if (bm != null)
{
imageView.SetImageBitmap(bm);
}
}
}
catch (Exception e)
{
Console.WriteLine (Bitmap creation failed:
+ e);
}
}
Notice in the GetView function we are using the CustomCell layout for each row; we also have a private method for creating our bitmaps from each model's byte array.
If we have a look at the current implementation, what do we notice here?
We are creating a bitmap every time the cell requires this data again for the view; is this efficient? No, we should be reusing bitmaps and memory