81
Creare app native su iOS, Android, Mac & Windows in C# Introduzione a Xamarin.Android

Xamarin.Android Introduction

Embed Size (px)

Citation preview

Page 1: Xamarin.Android Introduction

Creare app native su iOS, Android, Mac & Windows in C#

Introduzione a Xamarin.Android

Page 2: Xamarin.Android Introduction

Gli speaker di oggi

Guido MagrinXamarin & Microsoft Student Partner

Xamarin Certified Developer

@GuidoMagrin

Page 3: Xamarin.Android Introduction

Dove trovo le slide?

http://www.slideshare.net/guidomagrin

Page 4: Xamarin.Android Introduction

Gli Xamarin Student Partner

https://www.facebook.com/XSAMilano

Page 5: Xamarin.Android Introduction

Oggi parleremo di…

Xamarin.Android

Page 6: Xamarin.Android Introduction

Chi ha giàsentito parlare diXamarin.Android?

Page 7: Xamarin.Android Introduction

Xamarin + Xamarin.FormsApproccio offerto da Xamarin.Forms: Codice UI condiviso, controlli nativi

Approccio tradizionale di Xamarin

Shared UI Code

Page 8: Xamarin.Android Introduction

.NET Android APIs | 100% coverage

Page 9: Xamarin.Android Introduction

Qualsiasi cosa si possa fare inJava può essere fatta in C#

con Xamarin in Visual Studio

Page 10: Xamarin.Android Introduction

Xamarin StudioPC o Mac

Plugin Visual Studio VS 2010 e

superiore

Ambienti di Sviluppo

Page 11: Xamarin.Android Introduction

Integrazione in Visual Studio

Una soluzione sola per:• iOS• Android• Windows Phone• Windows Store

Tutti i plugin e le funzioni di Visual Studio:• ReSharper• Team Foundation Server

Page 12: Xamarin.Android Introduction

Integrazione in Visual Studio

Debugging su:• Emulatori• Dispositivi

Integrati nella toolbar:• Stato• Logs• Lista di dispositivi

Page 13: Xamarin.Android Introduction

Xamarin Studio

• Ottimizzato per lo sviluppo cross-platform

• Accedi alle API native con l’autocompletamento

• Designer per Android e iOS

• Debugging avanzato su emulatore o dispositivo

Page 14: Xamarin.Android Introduction

Designer per Xamarin Android• Il migliore designer per Android

• Disponibile per• Xamarin Studio • Visual Studio

• Crea facilmente l’interfaccia utente tramite drag & drop

• Affronta facilmente il problema del rescaling e della frammentazione di Android.

• Layout salvati in file XML Android standard

Page 15: Xamarin.Android Introduction

Cosa impareremo oggi?

• The package• Activities• Liste

Page 16: Xamarin.Android Introduction

The package

Page 17: Xamarin.Android Introduction

The package

The build process bundles the app into a single file with .apk extension.

It’s the package that needs to be uploaded in the Google Store to publish the app.

Page 18: Xamarin.Android Introduction

Permissions

The manifest file controls which features of the platform the app can use.

Page 19: Xamarin.Android Introduction

Images and screen density

• Android runs on many devices withdifferent screens and resolutions

• You supply the images in different sizeswith the same name

• You distinguish them applying a naming convention to the folder where the imageis stored

Page 20: Xamarin.Android Introduction

Images and screen density

• Every application should have an icon and a label

• It’s set in the manifest file

Page 21: Xamarin.Android Introduction

Icons and label

• Also activities can have their own icon and label

• They are displayed in the navigation bar

• They are defined in the Activity attribute[Activity(Label = "AndroidFundamentals", MainLauncher = true, Icon = "@drawable/icon")]public class MainActivity : Activity{ ...}

Page 22: Xamarin.Android Introduction

API levels

• Every Android version is identified by:– Version number (4.4, 5.1, etc.)– Nickname (Kit Kat, Lollipop, etc.)– API Level (19, 22, etc.)

• Every device supports a specific API level• It’s helpful to understand if an app can run on a

specific device

Page 23: Xamarin.Android Introduction

API levels

• In the properties of the project you can define:– Target API: the API level used to build the package– Minimum API: the minimum set of supported API level– Target Android version: API level that the app expects to

use

• If API Level < Minimum API the app won’t be installed

Page 24: Xamarin.Android Introduction

API Level Check

• If API Level < Target API some APIs mightn’t be available

• You can detect, in code, the current API Level:

if (Android.OS.Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop){ //use APIs that are available in Lollipop}else{ //fallback to old APIs}

Page 25: Xamarin.Android Introduction

Resources

• Resources can be managed using naming conventions applied to the folder

• Examples:– resources/drawable-it: it contains the images used on an

Italian device– layout-land: it contains the layouts to use in landscape

mode• The Build Action must be set to AndroidResource

Page 26: Xamarin.Android Introduction

Resources

• Layout: interfaces• Drawable: images• Values: generic strings (localization)• Color: XML files that define colors

Page 27: Xamarin.Android Introduction

Package

DEMO

Page 28: Xamarin.Android Introduction

La prima appXamarin.Forms

Page 29: Xamarin.Android Introduction

Domanda 1

Un’applicazione Android funziona senza vincoli particolari su qualsiasi telefono sul quale sia installato Android:

a) Verob) Falso

Page 30: Xamarin.Android Introduction

Domanda 1

Un’applicazione Android funziona senza vincoli particolari su qualsiasi telefono sul quale sia installato Android:

a) Verob) Falso

Page 31: Xamarin.Android Introduction

Domanda 2

Come si chiama il file tramite il quale posso modificare le impostazioni di un package Android?

a) Paperb) Resourcesc) Manifestd) Document

Page 32: Xamarin.Android Introduction

Domanda 2

Come si chiama il file tramite il quale posso modificare le impostazioni di un package Android?

a) Paperb) Resourcesc) Manifestd) Document

Page 33: Xamarin.Android Introduction

Domanda 3

Quali sono i tipi di Resources disponibili in un’app Android?a) Layout, Images, Values, Brushesb) Layout, Drawables, Values, Colorc) Disposition, Drawables, Enumerables, Colord) UIDefine, Images, Enumerables, Brushes

Page 34: Xamarin.Android Introduction

Domanda 3

Quali sono i tipi di Resources disponibili in un’app Android?a) Layout, Images, Values, Brushesb) Layout, Drawables, Values, Colorc) Disposition, Drawables, Enumerables, Colord) UIDefine, Images, Enumerables, Brushes

Page 35: Xamarin.Android Introduction

Activities

Page 36: Xamarin.Android Introduction

Activities

• An activity is a page that shows some content to the user.

• An application is usually composed by multiple activities.

Page 37: Xamarin.Android Introduction

Activities

• In Xamarin, an Activity is composed by:– A XML file, that describes the layout (optional, it can be

done also by code)– A code behind class, that manages the interactions with

the UI<?xml version="1.0" encoding="utf-8"?><LinearLayout ...> <TextView ... /> <EditText ... /> <Button ... /></LinearLayout>

public class MainActivity : Activity{

...}

UI defined with XML C# class that inherits from Activity and it’s

decorated with the ActivityAttribute

Page 38: Xamarin.Android Introduction

The Main Activity

It’s the activity that is automatically launched when the user starts an app

The MainLauncher property of the Activity

attribute is used to define the main activity[Activity(MainLauncher = true]

public class MainActivity : Activity{

...}

Page 39: Xamarin.Android Introduction

Access to controls

To gain access to a control in code you need to assign an IDAssign an ID in the XML <TextView

android:id="@+id/PhoneNumber" />

// aapt resource value: 0x7f050000public const int PhoneNumber = 2131034112;

TextView phoneNumberView = this.FindViewById<TextView>(Resource.Id.PhoneNumber);

The build processgenerates a resource

You use the id toaccess to the control

Page 40: Xamarin.Android Introduction

Dialogs

The AlertDialog class is used to display modal messages

var dialog = new AlertDialog.Builder(this);

dialog.SetTitle("Title");dialog.SetMessage("Message Goes Here");

dialog.SetNegativeButton("No", (sender, args) => { });dialog.SetNeutralButton("Maybe", (sender, args) => { });dialog.SetPositiveButton("Yes", (sender, args) => { });

dialog.Show();

Page 41: Xamarin.Android Introduction

Intents

• Activities are decoupled: they aren’t directly connected.

• You can use Intents to exchange messages with the operating system or with another activity

• Very similar concept to messages in the MVVM pattern

Page 42: Xamarin.Android Introduction

Intents to launch another activity

• You use an intent to redirect the user to another page of the application

• You pass, as parameter, the type of the destination activity

var intent = new Intent(this, typeof(CallDetailActivity));this.StartActivity(intent);

Type of the activity to create

Page 43: Xamarin.Android Introduction

Intents to pass data to another activity

• You can use Extras to pass data from one activity to another

Value

var intent = new Intent(this, typeof(CallDetailActivity));intent.PutStringArrayListExtra("phone_numbers", new[] { phoneNumberText.Text});this.StartActivity(intent); Key

Different Put methods to support various data types

Page 44: Xamarin.Android Introduction

Intent to retrieve data from another activity

• You get the parameter in the OnCreate() method of the Activity class

• It’s exposed by the Intent object

public class CallDetailActivity : Activity{ protected override void OnCreate(Bundle bundle) { IList<string> parameters = Intent.Extras.GetStringArrayList("phone_numbers"); }}

Key

KeyValue

Page 45: Xamarin.Android Introduction

Intents to launch built-in activities

• The Intent class can be used to launch a built-in activity

• Use the Intent enumerator to choose the activity’s type

var callIntent = new Intent(Intent.ActionCall);callIntent.SetData(Android.Net.Uri.Parse("tel:" + phoneNumber));StartActivity(callIntent);

Page 46: Xamarin.Android Introduction

The activity’s lifecicle

• Active: the activity is visible and running• Paused: the device is in sleep mode, it’s kept in

memory• Backgrounded: the activity is no more in foreground,

it’s kept in memory if possible• Restarted: the activity is created from scratch

Page 47: Xamarin.Android Introduction

The activity’s lifecicle

The Activity class offers multiple methods to override to manage the different states of the activity’s lifecycle

Page 48: Xamarin.Android Introduction

Configuration changes

• Android destroys and recreate the activity every time the configuration changes:– Orientation change– Keyboard displayed– Device connected to a dock

• It’s important to save the state of the activity, in case a configuration change happens

Page 49: Xamarin.Android Introduction

Activities

DEMO

Page 50: Xamarin.Android Introduction

La prima appXamarin.Forms

Page 51: Xamarin.Android Introduction

Domanda 1

Per mostrare del contenuto ad un utente devo usare il seguente controllo:

a) Pageb) Intentc) Activityd) Dialog

Page 52: Xamarin.Android Introduction

Domanda 1

Per mostrare del contenuto ad un utente devo usare il seguente controllo:

a) Pageb) Intentc) Activityd) Dialog

Page 53: Xamarin.Android Introduction

Domanda 2

Per navigare tra diverse Activities uso:a) Pointerb) Intentc) Navigatord) Arrow

Page 54: Xamarin.Android Introduction

Domanda 2

Per navigare tra diverse Activities uso:a) Pointerb) Intentc) Navigatord) Arrow

Page 55: Xamarin.Android Introduction

Domanda 3

Un’Activity è composta dalle seguenti due componenti:a) HTML + Code Behind (Java)b) XML + Code Behind (C#)c) UML + linksd) XAML + Code Behind (C#)

Page 56: Xamarin.Android Introduction

Domanda 3

Un’Activity è composta dalle seguenti due componenti:a) HTML + Code Behind (Java)b) XML + Code Behind (C#)c) UML + linksd) XAML + Code Behind (C#)

Page 57: Xamarin.Android Introduction

Saving state

DEMO

Page 58: Xamarin.Android Introduction

Managing lists

Page 59: Xamarin.Android Introduction

Displaying lists

• ListView and GridView are used to display collections of data

• They rely on the concept of adapterto define the data to display

• Adapters are pieces of code that create the UI for a row

Page 60: Xamarin.Android Introduction

Adapters

var pn = new List<string>();pn.Add("Title 1");pn.Add("Title 2");pn.Add("Title 3");

Adapter

The adapter creates a TextView for each item

Page 61: Xamarin.Android Introduction

ArrayAdapter

ArrayAdapter is a built-in adapter to display a collection of strings.

await client.GetCharactersForSeriesAsync();List<string> list = response.Results.Select(x => x.Name).ToList();

ListView listView = this.FindViewById<ListView>(Resource.Id.Comics);

listView.Adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleListItem1, list);

The layout to useThe data to display

Page 62: Xamarin.Android Introduction

Multiple layouts built-in

They are available using the enumeratorAndroid.Resource.Layout

Page 63: Xamarin.Android Introduction

Handling the selection

• Subscribe to the ItemClick event of the ListViewListView listView = this.FindViewById<ListView>(Resource.Id.Comics);listView.ItemClick += (sender, args) =>{

...};

listView.ItemClick += (sender, args) =>{

string name = list[args.Position];};

Page 64: Xamarin.Android Introduction

Lists

DEMO

Page 65: Xamarin.Android Introduction

La prima appXamarin.Forms

Page 66: Xamarin.Android Introduction

Domanda 1

Quali dei seguenti controlli possono essere utilizzati per mostrare una lista?

a) ListViewb) ImageViewc) ComboBoxd) GridView

Page 67: Xamarin.Android Introduction

Domanda 1

Quali dei seguenti controlli possono essere utilizzati per mostrare una lista?

a) ListViewb) ImageViewc) ComboBoxd) GridView

Page 68: Xamarin.Android Introduction

Domanda 2

Quali dei seguenti controlli possono essere utilizzati per mostrare una lista?

a) ListViewb) ImageViewc) ComboBoxd) GridView

Page 69: Xamarin.Android Introduction

Domanda 2

Quali dei seguenti controlli possono essere utilizzati per mostrare una lista?

a) ListViewb) ImageViewc) ComboBoxd) GridView

Page 70: Xamarin.Android Introduction

Custom adapters

• If you need to define a custom row layout, you need to use a custom adapter

• A custom adapter needs to implement BaseAdapter<T>

• You need to implement the four required methods:public abstract class BaseAdapter<T> : BaseAdapter{ public abstract View GetView(int position, View convertView, ViewGroup parent);

public abstract T this[int position] { get; } public abstract int Count { get; } public abstract long GetItemId(int position);}

Page 71: Xamarin.Android Introduction

LayoutInflator

• It’s a library class that takes the resource file andreturns a View hierarchy

• Every Activity has a LayoutInflator under the hood

<RelativeLayout ...> <ImageView ... /> <TextView ... /> <TextView ... /></RelativeLayout>

LayoutInflator

Page 72: Xamarin.Android Introduction

Creating a custom row

• The GetView() method of the custom adapter uses the LayoutInflater to create the row starting from a layoutview = this.context.LayoutInflater.Inflate(Resource.Layout.CharacterRow, parent, false);

<RelativeLayout ...> <ImageView ... /> <TextView ... /> <TextView ... /></RelativeLayout>

Page 73: Xamarin.Android Introduction

ListView Layout reuse

• ListView maintains the layouts only for the rows that are visible to the user

• The GetView() method of the custom adapter will receive a view to reuse if one is available

public override View GetView(int position, View convertView, ViewGroup parent){

//Cell reuse...var view = convertView;

if (convertView == null){

view = this.context.LayoutInflater.Inflate(Resource.Layout.CharacterRow, parent, false);

}}

Page 74: Xamarin.Android Introduction

Custom lists

DEMO

Page 75: Xamarin.Android Introduction

La prima appXamarin.Forms

Page 76: Xamarin.Android Introduction

Domanda 1

Cosa devo implementare quando vado a realizzare un Custom Adapter?

a) MyAdapter<T>b) BaseAdapter<T>c) CustomAdapter<T>d) CommonAdapter<T>

Page 77: Xamarin.Android Introduction

Domanda 1

Cosa devo implementare quando vado a realizzare un Custom Adapter?

a) MyAdapter<T>b) BaseAdapter<T>c) CustomAdapter<T>d) CommonAdapter<T>

Page 78: Xamarin.Android Introduction

Workingwith files

Page 79: Xamarin.Android Introduction

Files and foldersTo create files and folder you can leverage the basic .NET APIs (System.IO)• Context.CacheDir

– Temporary files that can be deleted by the system anytime• Context.ExternalCacheDir

– Temporary files that are removed when the app is deleted• Android.OS.Environment.ExternalStorageDirectory

.Path– Access to external SD, it requires a capability in the manifest

• Environment.GetFolderPath(Environment.SpecialFolder.Personal)– Local storage of the application

Page 80: Xamarin.Android Introduction

Working with files and folders

DEMO

Page 81: Xamarin.Android Introduction

Grazie per l’attenzione

Guido MagrinXamarin Student Partner

@GuidoMagrin