xamarin.android introduction
Post on 11-Feb-2017
191 Views
Preview:
TRANSCRIPT
Creare app native su iOS, Android, Mac & Windows in C#
Introduzione a Xamarin.Android
Gli speaker di oggi
Guido MagrinXamarin & Microsoft Student Partner
Xamarin Certified Developer
@GuidoMagrin
Dove trovo le slide?
http://www.slideshare.net/guidomagrin
Gli Xamarin Student Partner
https://www.facebook.com/XSAMilano
Oggi parleremo di…
Xamarin.Android
Chi ha giàsentito parlare diXamarin.Android?
Xamarin + Xamarin.FormsApproccio offerto da Xamarin.Forms: Codice UI condiviso, controlli nativi
Approccio tradizionale di Xamarin
Shared UI Code
.NET Android APIs | 100% coverage
Qualsiasi cosa si possa fare inJava può essere fatta in C#
con Xamarin in Visual Studio
Xamarin StudioPC o Mac
Plugin Visual Studio VS 2010 e
superiore
Ambienti di Sviluppo
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
Integrazione in Visual Studio
Debugging su:• Emulatori• Dispositivi
Integrati nella toolbar:• Stato• Logs• Lista di dispositivi
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
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
Cosa impareremo oggi?
• The package• Activities• Liste
The package
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.
Permissions
The manifest file controls which features of the platform the app can use.
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
Images and screen density
• Every application should have an icon and a label
• It’s set in the manifest file
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{ ...}
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
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
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}
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
Resources
• Layout: interfaces• Drawable: images• Values: generic strings (localization)• Color: XML files that define colors
Package
DEMO
La prima appXamarin.Forms
Domanda 1
Un’applicazione Android funziona senza vincoli particolari su qualsiasi telefono sul quale sia installato Android:
a) Verob) Falso
Domanda 1
Un’applicazione Android funziona senza vincoli particolari su qualsiasi telefono sul quale sia installato Android:
a) Verob) Falso
Domanda 2
Come si chiama il file tramite il quale posso modificare le impostazioni di un package Android?
a) Paperb) Resourcesc) Manifestd) Document
Domanda 2
Come si chiama il file tramite il quale posso modificare le impostazioni di un package Android?
a) Paperb) Resourcesc) Manifestd) Document
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
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
Activities
Activities
• An activity is a page that shows some content to the user.
• An application is usually composed by multiple activities.
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
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{
...}
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
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();
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
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
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
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
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);
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
The activity’s lifecicle
The Activity class offers multiple methods to override to manage the different states of the activity’s lifecycle
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
Activities
DEMO
La prima appXamarin.Forms
Domanda 1
Per mostrare del contenuto ad un utente devo usare il seguente controllo:
a) Pageb) Intentc) Activityd) Dialog
Domanda 1
Per mostrare del contenuto ad un utente devo usare il seguente controllo:
a) Pageb) Intentc) Activityd) Dialog
Domanda 2
Per navigare tra diverse Activities uso:a) Pointerb) Intentc) Navigatord) Arrow
Domanda 2
Per navigare tra diverse Activities uso:a) Pointerb) Intentc) Navigatord) Arrow
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#)
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#)
Saving state
DEMO
Managing lists
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
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
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
Multiple layouts built-in
They are available using the enumeratorAndroid.Resource.Layout
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];};
Lists
DEMO
La prima appXamarin.Forms
Domanda 1
Quali dei seguenti controlli possono essere utilizzati per mostrare una lista?
a) ListViewb) ImageViewc) ComboBoxd) GridView
Domanda 1
Quali dei seguenti controlli possono essere utilizzati per mostrare una lista?
a) ListViewb) ImageViewc) ComboBoxd) GridView
Domanda 2
Quali dei seguenti controlli possono essere utilizzati per mostrare una lista?
a) ListViewb) ImageViewc) ComboBoxd) GridView
Domanda 2
Quali dei seguenti controlli possono essere utilizzati per mostrare una lista?
a) ListViewb) ImageViewc) ComboBoxd) GridView
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);}
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
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>
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);
}}
Custom lists
DEMO
La prima appXamarin.Forms
Domanda 1
Cosa devo implementare quando vado a realizzare un Custom Adapter?
a) MyAdapter<T>b) BaseAdapter<T>c) CustomAdapter<T>d) CommonAdapter<T>
Domanda 1
Cosa devo implementare quando vado a realizzare un Custom Adapter?
a) MyAdapter<T>b) BaseAdapter<T>c) CustomAdapter<T>d) CommonAdapter<T>
Workingwith files
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
Working with files and folders
DEMO
Grazie per l’attenzione
Guido MagrinXamarin Student Partner
@GuidoMagrin
top related