SlideShare a Scribd company logo
1 of 38
BUILDING WITH
XAMARIN 1
COMPSCI 732 / SOFTENG 750 – PART TWO,
LECTURE FIVE
Disclaimer: All images in this slide deck are used under the fair-use
policy and remain © their respective copyright holders.
AGENDA
• What is Xamarin?
• Environment setup
• Project structure
• Xamarin architecture
• XAML
• Elements & attributes, Naming, Data binding
• Page layouts
• StackLayout, Grid, RelativeLayout
• Lists
• Text lists, Pre-defined templates, Custom templates
WHAT IS XAMARIN?
• Microsoft’s cross-platform development
toolkit
• Designed to enable app development for
Android, iOS, Windows Mobile, & Windows
platforms.
• Xamarin performs cross-compilation rather
than being an interpreted language – it
provides performance near to native
applications.
• Leverages the power of the C# language and
the .Net Framework
ENVIRONMENT SETUP
1. Everything is handled through Microsoft’s
own development platform, Visual Studio.
2. Heading to
https://www.xamarin.com/download will let
you down load the free Visual Studio
Community Edition, with Xamarin support
pre-installed.
• If you already have VS, you can install Xamarin using
the dialog found at Tools  Get Tools & Features…
3. Point Xamarin to your Android SDK using
Options  search for “Android”  Android
Settings
PROJECT CREATION
• Xamarin allows developers to write three kinds of
apps:
• Xamarin.Android: Write fully native Android apps using
C# instead of Java
• Xamarin.iOS: Write fully native iOS apps using C#
instead of Objective-C / Swift
• Xamarin.Forms: Write cross-platform apps
• Even when using Xamarin.Android & Xamarin.iOS,
code can be shared between them using a Shared
Project. Thus, most logic can be shared cross-
platform without code duplication, while
completely separate native UIs can be developed.
• To create any of these project types:
• File  New  Project  Visual C#  (either Android,
iOS, or Cross-Platform)
PROJECT CREATION
1. New project  Cross-Platform  Xamarin
Forms
2. Pick a location, choose a project & solution
name (they can be the same), and select
“create directory”
3. Select “Blank App”, pick your supported
platforms, pick Xamarin Forms for the UI
technology, and “Shared Project” for code
sharing.
PROJECT STRUCTURE
• MyFirstXamarinApp: A shared project. Anything in here will
be shared between all platforms. Xamarin Forms code and
shared classes go here.
• *.Android, *.iOS: Resources in here will be used only on
Android, iOS, and Windows platforms, respectively.
• The native projects have C# versions of the building blocks
for those platforms (i.e. Activity for Android, AppDelegate
for iOS). By default, in a Forms project, these load an
instance of the App class – which is the class defined by the
shared App.xaml.
• The first time you create a Xamarin project, you may see
“class not found” errors in your code – these will be
resolved the first time you build (right-click a project 
build)
PROJECT STRUCTURE
Three main kinds of files to define a Xamarin.Forms
app:
• XAML
• Stands for “eXtensible Application Markup Language”
• An XML specification. Like HTML, allows developers to
define the visual structure of a particular page (screen)
of an app.
• Code-Behind
• A C# file implementing the behaviour for a particular
page (e.g. what happens when you click a button or
select an item in a list?)
• A XAML file and its associated code-behind are
compiled together into a single .Net class at runtime.
• Other classes
PROJECT STRUCTURE
• Xamarin Forms is built on top of the platform-
specific libraries, Xamarin.Android and
Xamarin.iOS.
• UI elements in Xamarin Forms are mapped to
native equivalents on the target platforms. If
Xamarin Forms is used exclusively to define
the UI, then we can achieve a 100% cross-
platform app.
• If we wish to provide platform-specific
features, we can do so by editing the
associated platform-specific project.
Xamarin Forms
Xamarin.Andr
oid
Xamarin.iOS
PROJECT STRUCTURE
LIVE PLAYER
• Running / debugging the app in the Live Player:
1. Choose “Live Player” when running the app
2. Download the Xamarin Live Player app on iOS or
Android
3. Scan the provided QR code
• Live editing XAML:
1. Right-click the code window containing your XAML
2. Choose “Live Run”
3. When you save your changes, they should appear on
the device.
• As usual, how well this works depends on the
quality of the network connection between the
device and development machine.
RUNNING ON DEVICE
• Connect your device via USB and select it from the
run menu
• Any defined virtual machines will also appear here
• Click the play button – or use hotkeys (F5 to run,
Ctrl + F5 to debug)
• Your app will be built for the target platform and
deployed to the target device.
• Can take some time to build the first time (but not
as long as some other tools we’ve seen!)
• Usually very quick to load on concurrent runs
RUNNING ON DEVICE
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:MyFirstXamarinApp"
x:Class="MyFirstXamarinApp.MainPage">
<Label Text="Welcome to Xamarin.Forms!"
VerticalOptions="Center"
HorizontalOptions="Center" />
</ContentPage>
DEBUGGING
• Full debugging! Set breakpoints, step into /
over / out, run to cursor, view values of
current objects in memory, etc.
MAKING A NEW PAGE
1. Right-click shared project, click Add  New
Item…
2. Select Xamarin.Forms  Content Page
3. Name the file on the bottom (e.g.
GreetingPage.xaml)
4. Choose “Add”
5. Two files will be created:
1. GreetingPage.xaml – to define the visual structure
2. GreetingPage.xaml.cs – to define the behavior of the
page
THE XAML
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="MyFirstXamarinApp.GreetingPage">
<ContentPage.Content>
<StackLayout>
<Label Text="Welcome to Xamarin.Forms!"
VerticalOptions="CenterAndExpand"
HorizontalOptions="CenterAndExpand" />
</StackLayout>
</ContentPage.Content>
</ContentPage>
This is a
ContentPage (for
diaplaying main
content)
The actual
content goes
here.
A StackLayout
arranges
children
vertically
(default) or
horizontally.
A Label displays
text.
The .Net class name of this
page. Will match the class
name of the code-behind.
THE CODE-BEHIND
using …
namespace MyFirstXamarinApp
{
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class GreetingPage : ContentPage
{
public GreetingPage ()
{
InitializeComponent ();
}
}
}
“using” similar to Java “import”
statements
Namespaces similar to Java packages –
except they are independent of folder
structure.
This is an
Attribute –
similar to
Java
annotations.
The class definition. “partial” means
that some of the class is defined in
this file, and some of it elsewhere
This class
extends
ContentPage.
In C#, there’s
no “extends”
or
“implements”
keywords –
you just use a
colon :
Constructor
Calling this method
will create and
display all on-screen
FIRST XAML EDITS
1. Remove the existing content in our page
2. Add a <Button> element as follows:
<Button HorizontalOptions="Center"
VerticalOptions="Center"
Text="Click Me!"
Clicked="Button_Clicked"></Button>
private void Button_Clicked(object sender, EventArgs e)
{
DisplayAlert("Alert Title", "Hello World", "Ok");
}
Define a
Button…
The button is centered
horizontally and vertically in
its parent
The button
will have the
text “Click
Me!”
When the button is clicked, a
method in the code-behind with this
name will be called.
This is the event
handler method in the
code-behind. When the method is called, “sender” will be the
button itself, and “e” will contain additional info
about the event.
Display an alert to
the user. Inherited
from ContentPage
RUNNING OUR HELLO WORLD
APP
1. Open App.xaml.cs (the code-behind for
App.xaml)
2. Change the MainPage property to point to a
new instance of GreetingPage
3. Run the app
namespace MyFirstXamarinApp
{
public partial class App : Application
{
public App ()
{
InitializeComponent();
MainPage = new GreetingPage();
}
…
}
}
XAMARIN ARCHITECTURE
• All Xamarin platforms are built on Mono – an
open-source version of Microsoft’s .Net
framework, for non-Windows platforms.
• Xamarin.Android – formerly known as “Mono
for Android”
• Xamarin.iOS – formerly known as “MonoTouch”
Xamarin Forms
Xamarin.Android Xamarin.iOS
Mono
XAMARIN ARCHITECTURE
• Mono for a particular platform provides:
• .Net Base Class Library (BCL): a collection of widely
used classes from the framework, well-known for
traditional .Net developers
• Native APIs for that particular platform
• The Native APIs are direct equivalents of
Android / iOS classes – but wrapped in C#. The
names of these classes will be familiar to
native developers for those platforms.
Xamarin Forms
Xamarin.Android Xamarin.iOS
.Net BCL .Net BCL
Native APIs Native APIs
XAMARIN.ANDROID
ARCHITECTURE
C# Code IL Mono Runtime
Compile
.Net Intermediate
Language (similar to
Java bytecode)
Native
Just-in-time (JIT)
Compilation
Happens at runtime.
Process similar to
standard .Net console,
desktop applications
XAMARIN.IOS ARCHITECTURE
• Different – because Apple doesn’t allow JIT
compilation!
• No “Mono Runtime” on iOS devices – everything’s
already native
• No JIT compiling – everything is compiled to Apple
machine code at build time.
C# Code IL
Compile
Mono IL
Native
+
Apple compiler,
ahead-of-time
(AOT)
XAMARIN.FORMS
ARCHITECTURE
• Xamarin.Forms.Core: Defines common code
and interfaces for Xamarin Forms components
• Implementation classes are provided by the
Android / iOS – specific libraries.
Xamarin Forms
Xamarin.Andr
oid
Xamarin.iOS
Xamarin.Forms.Core
Library
Xamarin.For
ms Android
impl
Xamarin.For
ms iOS impl
NAMING ELEMENTS
• Within XAML, we can give elements names using the x:Name
attribute. Remember the x:!
• We can now access the element with that name from the
code-behind!
• How? Setting the x:Name property results in the code
generation of the corresponding variable name, which will
be set at runtime when the XAML is read.
<StackLayout HorizontalOptions="Center" VerticalOptions="Center">
<Label Text="Hello World" x:Name="myLabel" />
<Slider ValueChanged="Slider_ValueChanged" />
</StackLayout>
private void Slider_ValueChanged(object sender, ValueChangedEventArgs e)
{
myLabel.Text = String.Format("Value is {0:F2}", e.NewValue);
}
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")]
private global::Xamarin.Forms.Label myLabel;
Generated code in GreetingPage.xaml.g.cs
DATA BINDING
• Allows us to bind the value of a property of one
object (usually a UI element) to the value of some
other property.
• When a bound property changes, its data source will
also change, and vice versa.
• Let’s bind our label’s Text property to our slider’s
Value property:
• This works, but our Label won’t be nicely
formatted.
<Label Text="{Binding Source={x:Reference mySlider}, Path=Value}" x:Name="myLabel" />
<Slider x:Name="mySlider" />
<Label Text="{Binding
Source={x:Reference mySlider},
Path=Value,
StringFormat='Value is {0:F2}'}" x:Name="myLabel" />
DATA BINDING
• We can also set a BindingContext for an
element, rather than individually set the
Source:
<Label BindingContext="{x:Reference mySlider}"
Text="{Binding
Path=Value,
StringFormat='Value is {0:F2}'}"
Opacity="{Binding
Path=Value }"
x:Name="myLabel" />
DATA BINDING
• BindingContext of a parent element is
inherited by all its descendants.
<StackLayout BindingContext="{x:Reference mySlider}"
HorizontalOptions="Center"
VerticalOptions="Center">
<BoxView Color="Red" Opacity="{Binding Value}" />
<Label Text="{Binding Value, StringFormat='Value is {0:F2}'}"
Opacity="{Binding Value}"
x:Name="myLabel" />
<Slider x:Name="mySlider" />
</StackLayout>
XAML COMPILATION
• XAML is not compiled by default – it is included in the
built package and parsed when needed.
• This behaviour is to promote backwards compatibility,
but we can enable XAML compilation to achieve several
benefits:
• Compile-time checking of XAML to detect erors
• Reduced loading time
• Reduced file size
• To do this, add the following Attribute to the
AssemblyInfo.cs file:
using Xamarin.Forms.Xaml;
…
[assembly: XamlCompilation (XamlCompilationOptions.Compile)]
PAGE LAYOUTS - STACKLAYOUT
• Layout child elements in a line – either vertical (default) or
horizontal
• Set the StackLayout’s Orientation property to change this.
• By default, StackLayout will expand to fill its parent
• We can change this behaviour by setting the VerticalOptions and / or
HorizontalOptions properties.
<StackLayout BackgroundColor="Yellow">
<Label Text="Label 1"/>
<Label Text="Label 2"/>
<Label Text="Label 3"/>
</StackLayout>
<StackLayout BackgroundColor="Yellow"
VerticalOptions="Center">
<Label Text="Label 1"/>
<Label Text="Label 2"/>
<Label Text="Label 3"/>
</StackLayout>
PAGE LAYOUTS - STACKLAYOUT
• Can set the Spacing between child elements
• Default value is 6, meaning a small amount of
spacing between child elements.
• Can set the Padding around child elements
• Default value is 0 each side
<StackLayout BackgroundColor="Yellow"
VerticalOptions="Center"
HorizontalOptions="Center"
Spacing="50"
Padding="10, 20, 30, 40">
<Label Text="Label 1" BackgroundColor="AliceBlue"/>
<Label Text="Label 2" BackgroundColor="AliceBlue"/>
<Label Text="Label 3" BackgroundColor="AliceBlue"/>
</StackLayout>
Padding left: 10
Padding top: 20
Paddin
g
right:
30
Padding bottom:
40
Spacing: 50
PAGE LAYOUTS - STACKLAYOUT
• Can easily nest StackLayouts (or any other
layouts):
<StackLayout VerticalOptions="Center"
HorizontalOptions="Center"
Orientation="Horizontal"
Spacing="20"
Padding="40">
<StackLayout>
<Image Source="http://placehold.it/100x100" />
<Label Text="Label 1"/>
</StackLayout>
<Label Text="Label 2"/>
<Label Text="Label 3"/>
</StackLayout>
PAGE LAYOUTS - GRID
• Layout components in rows & columns
• Configurable spacing between elements
• RowSpacing and ColumnSpacing attributes
• Expands to fill entire parent by default
<Grid BackgroundColor="Yellow">
<Label Grid.Row="0" Grid.Column="0" Text="Label 1" BackgroundColor="LightGray"/>
<Label Grid.Row="0" Grid.Column="1" Text="Label 2" BackgroundColor="LightGray"/>
<Label Grid.Row="1" Grid.Column="0" Text="Label 3" BackgroundColor="LightGray"/>
<Label Grid.Row="1" Grid.Column="1" Text="Label 4" BackgroundColor="LightGray"/>
</Grid>
Since the parent is a Grid, our children
have extra attributes available, which
belong to the Grid.
PAGE LAYOUTS - GRID
• Children can span multiple rows / columns
<Grid BackgroundColor="Yellow"
RowSpacing="20"
ColumnSpacing="20"
Padding="20">
<Label Grid.Row="0" Grid.Column="0"
Text="Label 1" BackgroundColor="LightGray"/>
<Label Grid.Row="0" Grid.Column="1"
Text="Label 2" BackgroundColor="LightGray"/>
<Label Grid.Row="1" Grid.Column="0"
Text="Label 3" BackgroundColor="LightGray"/>
<Label Grid.Row="1" Grid.Column="1"
Text="Label 4" BackgroundColor="LightGray"/>
<Label Grid.Row="2" Grid.Column="0"
Grid.ColumnSpan="2"
Text="Two Columns" BackgroundColor="LightGray"/>
<Label Grid.Row="0" Grid.Column="2"
Grid.RowSpan="3"
Text="Three Rows" BackgroundColor="LightGray"/>
</Grid>
PAGE LAYOUTS - GRID
• By default, all rows are the same size, and all columns
are the same size.
• Can change this using Grid.RowDefinitions and
Grid.ColumnDefinitions
• In the below example, the first row is 100 units tall, the
second row takes up 2/3 of the remaining space, and the last
row takes up 1/3 of the space.
<Grid BackgroundColor="Yellow"
RowSpacing="20"
ColumnSpacing="20"
Padding="20">
<Grid.RowDefinitions>
<RowDefinition Height="100"/>
<RowDefinition Height="2*" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Label Grid.Row="0" Grid.Column="0" …/>
<Label Grid.Row="0" Grid.Column="1" …/>
<Label Grid.Row="1" Grid.Column="0" …/>
<Label Grid.Row="1" Grid.Column="1" …/>
<Label Grid.Row="2" Grid.Column="0" …/>
</Grid>
PAGE LAYOUTS - RELATIVE
• Allows us to specify the positions of elements
relative to parent and / or sibling elements.
• Width & Height constraints, relative to parent
• The following code means…
<RelativeLayout>
<BoxView Color="Red" x:Name="redBox"
RelativeLayout.WidthConstraint="{ConstraintExpression
Type=RelativeToParent,
Property=Width,
Factor=1}"
RelativeLayout.HeightConstraint="{ConstraintExpression
Type=RelativeToParent,
Property=Height,
Factor=0.3}"/>
</RelativeLayout>
Set the Width
to be 100% of
the parent’s
width
Set the Height
to be 30% of
the parent’s
height
PAGE LAYOUTS - RELATIVE
• Can define other constraints too:
• WidthConstraint, HeightConstraint
• XConstraint, YConstraint
• BoundsConstraint
• Can define relative to the properties of
siblings, e.g:
<RelativeLayout>
<BoxView Color="Red" x:Name="redBox" … />
<BoxView Color="LightGray"
RelativeLayout.YConstraint="{ConstraintExpression
Type=RelativeToView,
ElementName=redBox,
Property=Height,
Factor=1,
Constant=20}"/>
</RelativeLayout>
Set the Y value to be equal to
100% of the Height of the redBox,
plus 20.
USEFUL RESOURCES
• eBook (free) – “Creating Mobile Apps with
Xamarin.Forms”, First Edition:

More Related Content

Similar to CS732-SE750-Part2-Lecture05-Xamarin.pptx

Designing mobile applications with xamarin
Designing mobile applications with xamarinDesigning mobile applications with xamarin
Designing mobile applications with xamarinJerel Hass
 
NET Conf Bhubaneswar - Migrating your Xamarin.Forms app to .NET MAUI.pptx
NET Conf Bhubaneswar - Migrating your Xamarin.Forms app to .NET MAUI.pptxNET Conf Bhubaneswar - Migrating your Xamarin.Forms app to .NET MAUI.pptx
NET Conf Bhubaneswar - Migrating your Xamarin.Forms app to .NET MAUI.pptxLuis Beltran
 
How Xamarin Is Revolutionizing Mobile Development
How Xamarin Is Revolutionizing Mobile DevelopmentHow Xamarin Is Revolutionizing Mobile Development
How Xamarin Is Revolutionizing Mobile DevelopmentMentorMate
 
Your First Xamarin.Forms App
Your First Xamarin.Forms AppYour First Xamarin.Forms App
Your First Xamarin.Forms AppCraig Dunn
 
extending-and-optimizing-xamarin-forms-apps
extending-and-optimizing-xamarin-forms-appsextending-and-optimizing-xamarin-forms-apps
extending-and-optimizing-xamarin-forms-appsMatthew Soucoup
 
Mobile Cross-Platform App Development in C# with Xamarin
Mobile Cross-Platform App Development in C# with XamarinMobile Cross-Platform App Development in C# with Xamarin
Mobile Cross-Platform App Development in C# with XamarinNick Landry
 
Hire Xamarin App Developers: Building Apps With C# And .NET
Hire Xamarin App Developers: Building Apps With C# And .NETHire Xamarin App Developers: Building Apps With C# And .NET
Hire Xamarin App Developers: Building Apps With C# And .NETMoon Technolabs Pvt. Ltd.
 
Introduction to Xamarin.Forms
Introduction to Xamarin.FormsIntroduction to Xamarin.Forms
Introduction to Xamarin.FormsJames Montemagno
 
Xamarin.Forms: a cross-platform mobile UI toolkit - ConFoo 2016
Xamarin.Forms:  a cross-platform mobile UI toolkit - ConFoo 2016Xamarin.Forms:  a cross-platform mobile UI toolkit - ConFoo 2016
Xamarin.Forms: a cross-platform mobile UI toolkit - ConFoo 2016Guy Barrette
 
Xamarin Platform
Xamarin PlatformXamarin Platform
Xamarin PlatformRui Marinho
 
Introduction to Xamarin Philly Code Camp 2014
Introduction to Xamarin Philly Code Camp 2014Introduction to Xamarin Philly Code Camp 2014
Introduction to Xamarin Philly Code Camp 2014James Montemagno
 
Xamarin. Forms vs. Xamarin Native_ How to choose_.pdf
Xamarin. Forms vs. Xamarin Native_ How to choose_.pdfXamarin. Forms vs. Xamarin Native_ How to choose_.pdf
Xamarin. Forms vs. Xamarin Native_ How to choose_.pdfMoonTechnolabsPvtLtd
 
Why is xamarin the most popular framework for business app development
Why is xamarin the most popular framework for business app developmentWhy is xamarin the most popular framework for business app development
Why is xamarin the most popular framework for business app developmentFullestop
 
VS Saturday 2019 - Xamarin.Forms 4.x
VS Saturday 2019 - Xamarin.Forms 4.xVS Saturday 2019 - Xamarin.Forms 4.x
VS Saturday 2019 - Xamarin.Forms 4.xMarco Bortolin
 
Xamarin.forms vs. xamarin native how to choose the one you need
Xamarin.forms vs. xamarin native  how to choose the one you need Xamarin.forms vs. xamarin native  how to choose the one you need
Xamarin.forms vs. xamarin native how to choose the one you need MoonTechnolabsPvtLtd
 
Developing Cross-platform Native Apps with Xamarin
Developing Cross-platform Native Apps with XamarinDeveloping Cross-platform Native Apps with Xamarin
Developing Cross-platform Native Apps with Xamarindanhermes
 

Similar to CS732-SE750-Part2-Lecture05-Xamarin.pptx (20)

Designing mobile applications with xamarin
Designing mobile applications with xamarinDesigning mobile applications with xamarin
Designing mobile applications with xamarin
 
NET Conf Bhubaneswar - Migrating your Xamarin.Forms app to .NET MAUI.pptx
NET Conf Bhubaneswar - Migrating your Xamarin.Forms app to .NET MAUI.pptxNET Conf Bhubaneswar - Migrating your Xamarin.Forms app to .NET MAUI.pptx
NET Conf Bhubaneswar - Migrating your Xamarin.Forms app to .NET MAUI.pptx
 
How Xamarin Is Revolutionizing Mobile Development
How Xamarin Is Revolutionizing Mobile DevelopmentHow Xamarin Is Revolutionizing Mobile Development
How Xamarin Is Revolutionizing Mobile Development
 
Your First Xamarin.Forms App
Your First Xamarin.Forms AppYour First Xamarin.Forms App
Your First Xamarin.Forms App
 
extending-and-optimizing-xamarin-forms-apps
extending-and-optimizing-xamarin-forms-appsextending-and-optimizing-xamarin-forms-apps
extending-and-optimizing-xamarin-forms-apps
 
Mobile Cross-Platform App Development in C# with Xamarin
Mobile Cross-Platform App Development in C# with XamarinMobile Cross-Platform App Development in C# with Xamarin
Mobile Cross-Platform App Development in C# with Xamarin
 
Hire Xamarin App Developers: Building Apps With C# And .NET
Hire Xamarin App Developers: Building Apps With C# And .NETHire Xamarin App Developers: Building Apps With C# And .NET
Hire Xamarin App Developers: Building Apps With C# And .NET
 
Xamarin Overview
Xamarin OverviewXamarin Overview
Xamarin Overview
 
Introduction to Xamarin.Forms
Introduction to Xamarin.FormsIntroduction to Xamarin.Forms
Introduction to Xamarin.Forms
 
Xamarin.Forms: a cross-platform mobile UI toolkit - ConFoo 2016
Xamarin.Forms:  a cross-platform mobile UI toolkit - ConFoo 2016Xamarin.Forms:  a cross-platform mobile UI toolkit - ConFoo 2016
Xamarin.Forms: a cross-platform mobile UI toolkit - ConFoo 2016
 
Xamarin Platform
Xamarin PlatformXamarin Platform
Xamarin Platform
 
Introduction to Xamarin Philly Code Camp 2014
Introduction to Xamarin Philly Code Camp 2014Introduction to Xamarin Philly Code Camp 2014
Introduction to Xamarin Philly Code Camp 2014
 
An introduction to Xamarin
An introduction to XamarinAn introduction to Xamarin
An introduction to Xamarin
 
Xamarin. Forms vs. Xamarin Native_ How to choose_.pdf
Xamarin. Forms vs. Xamarin Native_ How to choose_.pdfXamarin. Forms vs. Xamarin Native_ How to choose_.pdf
Xamarin. Forms vs. Xamarin Native_ How to choose_.pdf
 
Why is xamarin the most popular framework for business app development
Why is xamarin the most popular framework for business app developmentWhy is xamarin the most popular framework for business app development
Why is xamarin the most popular framework for business app development
 
Introduction to Xamarin
Introduction to XamarinIntroduction to Xamarin
Introduction to Xamarin
 
Introduction to xamarin
Introduction to xamarinIntroduction to xamarin
Introduction to xamarin
 
VS Saturday 2019 - Xamarin.Forms 4.x
VS Saturday 2019 - Xamarin.Forms 4.xVS Saturday 2019 - Xamarin.Forms 4.x
VS Saturday 2019 - Xamarin.Forms 4.x
 
Xamarin.forms vs. xamarin native how to choose the one you need
Xamarin.forms vs. xamarin native  how to choose the one you need Xamarin.forms vs. xamarin native  how to choose the one you need
Xamarin.forms vs. xamarin native how to choose the one you need
 
Developing Cross-platform Native Apps with Xamarin
Developing Cross-platform Native Apps with XamarinDeveloping Cross-platform Native Apps with Xamarin
Developing Cross-platform Native Apps with Xamarin
 

Recently uploaded

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Neo4j
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Wonjun Hwang
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 

Recently uploaded (20)

E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 
Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024Build your next Gen AI Breakthrough - April 2024
Build your next Gen AI Breakthrough - April 2024
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
Bun (KitWorks Team Study 노별마루 발표 2024.4.22)
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 

CS732-SE750-Part2-Lecture05-Xamarin.pptx

  • 1. BUILDING WITH XAMARIN 1 COMPSCI 732 / SOFTENG 750 – PART TWO, LECTURE FIVE Disclaimer: All images in this slide deck are used under the fair-use policy and remain © their respective copyright holders.
  • 2. AGENDA • What is Xamarin? • Environment setup • Project structure • Xamarin architecture • XAML • Elements & attributes, Naming, Data binding • Page layouts • StackLayout, Grid, RelativeLayout • Lists • Text lists, Pre-defined templates, Custom templates
  • 3. WHAT IS XAMARIN? • Microsoft’s cross-platform development toolkit • Designed to enable app development for Android, iOS, Windows Mobile, & Windows platforms. • Xamarin performs cross-compilation rather than being an interpreted language – it provides performance near to native applications. • Leverages the power of the C# language and the .Net Framework
  • 4. ENVIRONMENT SETUP 1. Everything is handled through Microsoft’s own development platform, Visual Studio. 2. Heading to https://www.xamarin.com/download will let you down load the free Visual Studio Community Edition, with Xamarin support pre-installed. • If you already have VS, you can install Xamarin using the dialog found at Tools  Get Tools & Features… 3. Point Xamarin to your Android SDK using Options  search for “Android”  Android Settings
  • 5. PROJECT CREATION • Xamarin allows developers to write three kinds of apps: • Xamarin.Android: Write fully native Android apps using C# instead of Java • Xamarin.iOS: Write fully native iOS apps using C# instead of Objective-C / Swift • Xamarin.Forms: Write cross-platform apps • Even when using Xamarin.Android & Xamarin.iOS, code can be shared between them using a Shared Project. Thus, most logic can be shared cross- platform without code duplication, while completely separate native UIs can be developed. • To create any of these project types: • File  New  Project  Visual C#  (either Android, iOS, or Cross-Platform)
  • 6. PROJECT CREATION 1. New project  Cross-Platform  Xamarin Forms 2. Pick a location, choose a project & solution name (they can be the same), and select “create directory” 3. Select “Blank App”, pick your supported platforms, pick Xamarin Forms for the UI technology, and “Shared Project” for code sharing.
  • 7. PROJECT STRUCTURE • MyFirstXamarinApp: A shared project. Anything in here will be shared between all platforms. Xamarin Forms code and shared classes go here. • *.Android, *.iOS: Resources in here will be used only on Android, iOS, and Windows platforms, respectively. • The native projects have C# versions of the building blocks for those platforms (i.e. Activity for Android, AppDelegate for iOS). By default, in a Forms project, these load an instance of the App class – which is the class defined by the shared App.xaml. • The first time you create a Xamarin project, you may see “class not found” errors in your code – these will be resolved the first time you build (right-click a project  build)
  • 8. PROJECT STRUCTURE Three main kinds of files to define a Xamarin.Forms app: • XAML • Stands for “eXtensible Application Markup Language” • An XML specification. Like HTML, allows developers to define the visual structure of a particular page (screen) of an app. • Code-Behind • A C# file implementing the behaviour for a particular page (e.g. what happens when you click a button or select an item in a list?) • A XAML file and its associated code-behind are compiled together into a single .Net class at runtime. • Other classes
  • 9. PROJECT STRUCTURE • Xamarin Forms is built on top of the platform- specific libraries, Xamarin.Android and Xamarin.iOS. • UI elements in Xamarin Forms are mapped to native equivalents on the target platforms. If Xamarin Forms is used exclusively to define the UI, then we can achieve a 100% cross- platform app. • If we wish to provide platform-specific features, we can do so by editing the associated platform-specific project. Xamarin Forms Xamarin.Andr oid Xamarin.iOS
  • 11. LIVE PLAYER • Running / debugging the app in the Live Player: 1. Choose “Live Player” when running the app 2. Download the Xamarin Live Player app on iOS or Android 3. Scan the provided QR code • Live editing XAML: 1. Right-click the code window containing your XAML 2. Choose “Live Run” 3. When you save your changes, they should appear on the device. • As usual, how well this works depends on the quality of the network connection between the device and development machine.
  • 12. RUNNING ON DEVICE • Connect your device via USB and select it from the run menu • Any defined virtual machines will also appear here • Click the play button – or use hotkeys (F5 to run, Ctrl + F5 to debug) • Your app will be built for the target platform and deployed to the target device. • Can take some time to build the first time (but not as long as some other tools we’ve seen!) • Usually very quick to load on concurrent runs
  • 13. RUNNING ON DEVICE <?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" xmlns:local="clr-namespace:MyFirstXamarinApp" x:Class="MyFirstXamarinApp.MainPage"> <Label Text="Welcome to Xamarin.Forms!" VerticalOptions="Center" HorizontalOptions="Center" /> </ContentPage>
  • 14. DEBUGGING • Full debugging! Set breakpoints, step into / over / out, run to cursor, view values of current objects in memory, etc.
  • 15. MAKING A NEW PAGE 1. Right-click shared project, click Add  New Item… 2. Select Xamarin.Forms  Content Page 3. Name the file on the bottom (e.g. GreetingPage.xaml) 4. Choose “Add” 5. Two files will be created: 1. GreetingPage.xaml – to define the visual structure 2. GreetingPage.xaml.cs – to define the behavior of the page
  • 16. THE XAML <?xml version="1.0" encoding="utf-8" ?> <ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="MyFirstXamarinApp.GreetingPage"> <ContentPage.Content> <StackLayout> <Label Text="Welcome to Xamarin.Forms!" VerticalOptions="CenterAndExpand" HorizontalOptions="CenterAndExpand" /> </StackLayout> </ContentPage.Content> </ContentPage> This is a ContentPage (for diaplaying main content) The actual content goes here. A StackLayout arranges children vertically (default) or horizontally. A Label displays text. The .Net class name of this page. Will match the class name of the code-behind.
  • 17. THE CODE-BEHIND using … namespace MyFirstXamarinApp { [XamlCompilation(XamlCompilationOptions.Compile)] public partial class GreetingPage : ContentPage { public GreetingPage () { InitializeComponent (); } } } “using” similar to Java “import” statements Namespaces similar to Java packages – except they are independent of folder structure. This is an Attribute – similar to Java annotations. The class definition. “partial” means that some of the class is defined in this file, and some of it elsewhere This class extends ContentPage. In C#, there’s no “extends” or “implements” keywords – you just use a colon : Constructor Calling this method will create and display all on-screen
  • 18. FIRST XAML EDITS 1. Remove the existing content in our page 2. Add a <Button> element as follows: <Button HorizontalOptions="Center" VerticalOptions="Center" Text="Click Me!" Clicked="Button_Clicked"></Button> private void Button_Clicked(object sender, EventArgs e) { DisplayAlert("Alert Title", "Hello World", "Ok"); } Define a Button… The button is centered horizontally and vertically in its parent The button will have the text “Click Me!” When the button is clicked, a method in the code-behind with this name will be called. This is the event handler method in the code-behind. When the method is called, “sender” will be the button itself, and “e” will contain additional info about the event. Display an alert to the user. Inherited from ContentPage
  • 19. RUNNING OUR HELLO WORLD APP 1. Open App.xaml.cs (the code-behind for App.xaml) 2. Change the MainPage property to point to a new instance of GreetingPage 3. Run the app namespace MyFirstXamarinApp { public partial class App : Application { public App () { InitializeComponent(); MainPage = new GreetingPage(); } … } }
  • 20. XAMARIN ARCHITECTURE • All Xamarin platforms are built on Mono – an open-source version of Microsoft’s .Net framework, for non-Windows platforms. • Xamarin.Android – formerly known as “Mono for Android” • Xamarin.iOS – formerly known as “MonoTouch” Xamarin Forms Xamarin.Android Xamarin.iOS Mono
  • 21. XAMARIN ARCHITECTURE • Mono for a particular platform provides: • .Net Base Class Library (BCL): a collection of widely used classes from the framework, well-known for traditional .Net developers • Native APIs for that particular platform • The Native APIs are direct equivalents of Android / iOS classes – but wrapped in C#. The names of these classes will be familiar to native developers for those platforms. Xamarin Forms Xamarin.Android Xamarin.iOS .Net BCL .Net BCL Native APIs Native APIs
  • 22. XAMARIN.ANDROID ARCHITECTURE C# Code IL Mono Runtime Compile .Net Intermediate Language (similar to Java bytecode) Native Just-in-time (JIT) Compilation Happens at runtime. Process similar to standard .Net console, desktop applications
  • 23. XAMARIN.IOS ARCHITECTURE • Different – because Apple doesn’t allow JIT compilation! • No “Mono Runtime” on iOS devices – everything’s already native • No JIT compiling – everything is compiled to Apple machine code at build time. C# Code IL Compile Mono IL Native + Apple compiler, ahead-of-time (AOT)
  • 24. XAMARIN.FORMS ARCHITECTURE • Xamarin.Forms.Core: Defines common code and interfaces for Xamarin Forms components • Implementation classes are provided by the Android / iOS – specific libraries. Xamarin Forms Xamarin.Andr oid Xamarin.iOS Xamarin.Forms.Core Library Xamarin.For ms Android impl Xamarin.For ms iOS impl
  • 25. NAMING ELEMENTS • Within XAML, we can give elements names using the x:Name attribute. Remember the x:! • We can now access the element with that name from the code-behind! • How? Setting the x:Name property results in the code generation of the corresponding variable name, which will be set at runtime when the XAML is read. <StackLayout HorizontalOptions="Center" VerticalOptions="Center"> <Label Text="Hello World" x:Name="myLabel" /> <Slider ValueChanged="Slider_ValueChanged" /> </StackLayout> private void Slider_ValueChanged(object sender, ValueChangedEventArgs e) { myLabel.Text = String.Format("Value is {0:F2}", e.NewValue); } [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Xamarin.Forms.Build.Tasks.XamlG", "0.0.0.0")] private global::Xamarin.Forms.Label myLabel; Generated code in GreetingPage.xaml.g.cs
  • 26. DATA BINDING • Allows us to bind the value of a property of one object (usually a UI element) to the value of some other property. • When a bound property changes, its data source will also change, and vice versa. • Let’s bind our label’s Text property to our slider’s Value property: • This works, but our Label won’t be nicely formatted. <Label Text="{Binding Source={x:Reference mySlider}, Path=Value}" x:Name="myLabel" /> <Slider x:Name="mySlider" /> <Label Text="{Binding Source={x:Reference mySlider}, Path=Value, StringFormat='Value is {0:F2}'}" x:Name="myLabel" />
  • 27. DATA BINDING • We can also set a BindingContext for an element, rather than individually set the Source: <Label BindingContext="{x:Reference mySlider}" Text="{Binding Path=Value, StringFormat='Value is {0:F2}'}" Opacity="{Binding Path=Value }" x:Name="myLabel" />
  • 28. DATA BINDING • BindingContext of a parent element is inherited by all its descendants. <StackLayout BindingContext="{x:Reference mySlider}" HorizontalOptions="Center" VerticalOptions="Center"> <BoxView Color="Red" Opacity="{Binding Value}" /> <Label Text="{Binding Value, StringFormat='Value is {0:F2}'}" Opacity="{Binding Value}" x:Name="myLabel" /> <Slider x:Name="mySlider" /> </StackLayout>
  • 29. XAML COMPILATION • XAML is not compiled by default – it is included in the built package and parsed when needed. • This behaviour is to promote backwards compatibility, but we can enable XAML compilation to achieve several benefits: • Compile-time checking of XAML to detect erors • Reduced loading time • Reduced file size • To do this, add the following Attribute to the AssemblyInfo.cs file: using Xamarin.Forms.Xaml; … [assembly: XamlCompilation (XamlCompilationOptions.Compile)]
  • 30. PAGE LAYOUTS - STACKLAYOUT • Layout child elements in a line – either vertical (default) or horizontal • Set the StackLayout’s Orientation property to change this. • By default, StackLayout will expand to fill its parent • We can change this behaviour by setting the VerticalOptions and / or HorizontalOptions properties. <StackLayout BackgroundColor="Yellow"> <Label Text="Label 1"/> <Label Text="Label 2"/> <Label Text="Label 3"/> </StackLayout> <StackLayout BackgroundColor="Yellow" VerticalOptions="Center"> <Label Text="Label 1"/> <Label Text="Label 2"/> <Label Text="Label 3"/> </StackLayout>
  • 31. PAGE LAYOUTS - STACKLAYOUT • Can set the Spacing between child elements • Default value is 6, meaning a small amount of spacing between child elements. • Can set the Padding around child elements • Default value is 0 each side <StackLayout BackgroundColor="Yellow" VerticalOptions="Center" HorizontalOptions="Center" Spacing="50" Padding="10, 20, 30, 40"> <Label Text="Label 1" BackgroundColor="AliceBlue"/> <Label Text="Label 2" BackgroundColor="AliceBlue"/> <Label Text="Label 3" BackgroundColor="AliceBlue"/> </StackLayout> Padding left: 10 Padding top: 20 Paddin g right: 30 Padding bottom: 40 Spacing: 50
  • 32. PAGE LAYOUTS - STACKLAYOUT • Can easily nest StackLayouts (or any other layouts): <StackLayout VerticalOptions="Center" HorizontalOptions="Center" Orientation="Horizontal" Spacing="20" Padding="40"> <StackLayout> <Image Source="http://placehold.it/100x100" /> <Label Text="Label 1"/> </StackLayout> <Label Text="Label 2"/> <Label Text="Label 3"/> </StackLayout>
  • 33. PAGE LAYOUTS - GRID • Layout components in rows & columns • Configurable spacing between elements • RowSpacing and ColumnSpacing attributes • Expands to fill entire parent by default <Grid BackgroundColor="Yellow"> <Label Grid.Row="0" Grid.Column="0" Text="Label 1" BackgroundColor="LightGray"/> <Label Grid.Row="0" Grid.Column="1" Text="Label 2" BackgroundColor="LightGray"/> <Label Grid.Row="1" Grid.Column="0" Text="Label 3" BackgroundColor="LightGray"/> <Label Grid.Row="1" Grid.Column="1" Text="Label 4" BackgroundColor="LightGray"/> </Grid> Since the parent is a Grid, our children have extra attributes available, which belong to the Grid.
  • 34. PAGE LAYOUTS - GRID • Children can span multiple rows / columns <Grid BackgroundColor="Yellow" RowSpacing="20" ColumnSpacing="20" Padding="20"> <Label Grid.Row="0" Grid.Column="0" Text="Label 1" BackgroundColor="LightGray"/> <Label Grid.Row="0" Grid.Column="1" Text="Label 2" BackgroundColor="LightGray"/> <Label Grid.Row="1" Grid.Column="0" Text="Label 3" BackgroundColor="LightGray"/> <Label Grid.Row="1" Grid.Column="1" Text="Label 4" BackgroundColor="LightGray"/> <Label Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" Text="Two Columns" BackgroundColor="LightGray"/> <Label Grid.Row="0" Grid.Column="2" Grid.RowSpan="3" Text="Three Rows" BackgroundColor="LightGray"/> </Grid>
  • 35. PAGE LAYOUTS - GRID • By default, all rows are the same size, and all columns are the same size. • Can change this using Grid.RowDefinitions and Grid.ColumnDefinitions • In the below example, the first row is 100 units tall, the second row takes up 2/3 of the remaining space, and the last row takes up 1/3 of the space. <Grid BackgroundColor="Yellow" RowSpacing="20" ColumnSpacing="20" Padding="20"> <Grid.RowDefinitions> <RowDefinition Height="100"/> <RowDefinition Height="2*" /> <RowDefinition Height="*" /> </Grid.RowDefinitions> <Label Grid.Row="0" Grid.Column="0" …/> <Label Grid.Row="0" Grid.Column="1" …/> <Label Grid.Row="1" Grid.Column="0" …/> <Label Grid.Row="1" Grid.Column="1" …/> <Label Grid.Row="2" Grid.Column="0" …/> </Grid>
  • 36. PAGE LAYOUTS - RELATIVE • Allows us to specify the positions of elements relative to parent and / or sibling elements. • Width & Height constraints, relative to parent • The following code means… <RelativeLayout> <BoxView Color="Red" x:Name="redBox" RelativeLayout.WidthConstraint="{ConstraintExpression Type=RelativeToParent, Property=Width, Factor=1}" RelativeLayout.HeightConstraint="{ConstraintExpression Type=RelativeToParent, Property=Height, Factor=0.3}"/> </RelativeLayout> Set the Width to be 100% of the parent’s width Set the Height to be 30% of the parent’s height
  • 37. PAGE LAYOUTS - RELATIVE • Can define other constraints too: • WidthConstraint, HeightConstraint • XConstraint, YConstraint • BoundsConstraint • Can define relative to the properties of siblings, e.g: <RelativeLayout> <BoxView Color="Red" x:Name="redBox" … /> <BoxView Color="LightGray" RelativeLayout.YConstraint="{ConstraintExpression Type=RelativeToView, ElementName=redBox, Property=Height, Factor=1, Constant=20}"/> </RelativeLayout> Set the Y value to be equal to 100% of the Height of the redBox, plus 20.
  • 38. USEFUL RESOURCES • eBook (free) – “Creating Mobile Apps with Xamarin.Forms”, First Edition:

Editor's Notes

  1. For columns: The same, except Grid.ColumnDefinitions, and ColumnDefinition. Definition can be “Auto” – meaning, wide / high enough to fit its children.