Académique Documents
Professionnel Documents
Culture Documents
1 of 19
https://msdn.microsoft.com/en-us/library/dn879698(d=printer).aspx
Once you've done the steps in Setup and install and Verify your Xamarin environment, this walkthrough shows you how
to build a basic Xamarin app (shown below) with native UI layers. With native UI, shared code resides in a portable class
library (PCL) and the individual platform projects contain the UI definitions.
Tip
You can find the complete source code for this project in the mobile-samples repository on GitHub.
If you have difficulties or run into errors, please post questions on forums.xamarin.com. Many errors can be resolved
21-11-2016 21:56
2 of 19
https://msdn.microsoft.com/en-us/library/dn879698(d=printer).aspx
by updating to the latest SDKs required by Xamarin, which are described in the Xamarin Release Notes for each
platform.
Note
Xamarin's developer documentation also offers several walkthroughs with both Quickstart and Deep Dive sections as
listed below. On all these pages, be sure that "Visual Studio" is selected in the upper right of the page to see Visual
Studio-specific walkthroughs.
Xamarin apps with native UI:
Hello, Android (simple app with one screen)
Hello, Android multiscreen (app with navigation between screens)
Android Fragments Walkthrough (used for master/detail screens, among other things)
Hello, iOS
Hello, iOS Multiscreen
Xamarin apps with Xamarin.Forms (shared UI)
Hello, Xamarin.Forms
Hello, Xamarin.Forms Multiscreen
21-11-2016 21:56
3 of 19
https://msdn.microsoft.com/en-us/library/dn879698(d=printer).aspx
In the NuGet window, select the Browse tab and search for Newtonsoft.
Select Newtonsoft.Json.
On the right side of the window, check the WeatherApp project (this is the only project in which you need
to install the package).
Ensure the Version field is set to the Latest stable version.
Click Install.
21-11-2016 21:56
4 of 19
public
public
public
public
public
public
string
string
string
string
string
string
https://msdn.microsoft.com/en-us/library/dn879698(d=printer).aspx
public Weather()
{
//Because labels bind to these values, set them to an empty string to
//ensure that the label appears on all platforms by default.
this.Title = " ";
this.Temperature = " ";
this.Wind = " ";
this.Humidity = " ";
this.Visibility = " ";
this.Sunrise = " ";
this.Sunset = " ";
}
}
}
4. Add another class to the PCL project named DataService.cs in which youll use to process JSON data from the
weather data service.
5. Replace the entire contents of DataService.cs with the following code:
C#
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Net.Http;
namespace WeatherApp
{
public class DataService
{
public static async Task<dynamic> getDataFromService(string queryString)
{
HttpClient client = new HttpClient();
var response = await client.GetAsync(queryString);
dynamic data = null;
if (response != null)
{
string json = response.Content.ReadAsStringAsync().Result;
data = JsonConvert.DeserializeObject(json);
}
return data;
}
}
}
6. Add a third class to the PCL named Core where youll put shared business logic, such as logic that forms a query
21-11-2016 21:56
5 of 19
https://msdn.microsoft.com/en-us/library/dn879698(d=printer).aspx
string with a zip code, calls the weather data service, and populates an instance of the Weather class.
7. Replace the contents of Core.cs with the following:
C#
21-11-2016 21:56
6 of 19
https://msdn.microsoft.com/en-us/library/dn879698(d=printer).aspx
using System;
using System.Threading.Tasks;
namespace WeatherApp
{
public class Core
{
public static async Task<Weather> GetWeather(string zipCode)
{
//Sign up for a free API key at http://openweathermap.org/appid
string key = "YOUR KEY HERE";
string queryString = "http://api.openweathermap.org/data/2.5
/weather?zip="
+ zipCode + ",us&appid=" + key + "&units=imperial";
//Make sure developers running this sample replaced the API key
if (key == "YOUR API KEY HERE")
{
throw new ArgumentException("You must obtain an API key from
openweathermap.org/appid and save it in the 'key' variable.");
}
dynamic results = await
DataService.getDataFromService(queryString).ConfigureAwait(false);
if (results["weather"] != null)
{
Weather weather = new Weather();
weather.Title = (string)results["name"];
weather.Temperature = (string)results["main"]["temp"] + " F";
weather.Wind = (string)results["wind"]["speed"] + "
mph";
weather.Humidity = (string)results["main"]["humidity"] + " %";
weather.Visibility = (string)results["weather"][0]["main"];
DateTime time = new System.DateTime(1970, 1, 1, 0, 0, 0, 0);
DateTime sunrise = time.AddSeconds((double)results["sys"]
["sunrise"]);
DateTime sunset = time.AddSeconds((double)results["sys"]
["sunset"]);
weather.Sunrise = sunrise.ToString() + " UTC";
weather.Sunset = sunset.ToString() + " UTC";
return weather;
}
else
{
return null;
}
}
}
}
8. Replace YOUR KEY HERE in the code with the API key you obtained in step 1 (it still needs quotes around it).
9. Delete MyClass.cs in the PCL because we won't be using it.
21-11-2016 21:56
7 of 19
https://msdn.microsoft.com/en-us/library/dn879698(d=printer).aspx
10. Build the WeatherApp PCL project to make sure the code is correct.
Tip
There are many other files in the project. Exploring them is beyond the scope of this topic, but if you want to
dive into the structure of an Android project a bit more, see Part 2 Deep Dive of the Hello Android topic on
xamarin.com.
2. Select and delete the default button that appears in the designer.
3. Open the Toolbox with View > Other Windows > Toolbox.
4. From the Toolbox, drag a RelativeLayout control onto the designer. You'll use this control as a parent container
for other controls.
Tip
If at any time the layout doesn't seem to display correctly, save the file and switching between the Design and
Source tabs to refresh.
5. In the Properties window, set the background property (in the Style group) to #545454.
6. From the Toolbox, drag a TextView control onto the RelativeLayout control.
7. In the Properties window, set these properties (note: it can help to sort the list alphabetically using the sort button
in the Properties window toolbar):
Property
Value
text
id
@+id/ZipCodeSearchLabel
layout_marginLeft
10dp
textColor
@android:color/white
21-11-2016 21:56
8 of 19
Property
Value
textStyle
bold
https://msdn.microsoft.com/en-us/library/dn879698(d=printer).aspx
Tip
Notice that many properties dont contain a drop-down list of values that you can select. It can be difficult to
guess what string value to use for any given property. For suggestions, try searching for the name of a property
in the R.attr class page.
Also, a quick web search often leads to a page on http://stackoverflow.com/ where others have used the same
property.
For reference, if you switch to Source view, you should see the following code for this element:
XML
<TextView
android:text="Search by Zip Code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/ZipCodeSearchLabel"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:textColor="@android:color/white"
android:textStyle="bold" />
8. From the Toolbox, drag a TextView control onto the RelativeLayout control and position it below the
ZipCodeSearchLabel control. You do this by dropping the new control on the appropriate edge of the existing
control; it helps to zoom the designer in somewhat for this.
9. In the Properties window, set these properties:
Property
Value
text
Zip Code
id
@+id/ZipCodeLabel
layout_marginLeft
10dp
layout_marginTop
5dp
21-11-2016 21:56
9 of 19
https://msdn.microsoft.com/en-us/library/dn879698(d=printer).aspx
android:text="Zip Code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/ZipCodeSearchLabel"
android:id="@+id/ZipCodeLabel"
android:layout_marginTop="5dp"
android:layout_marginLeft="10dp" />
10. From the Toolbox, drag a Number control onto the RelativeLayout, position it below the Zip Code label. Then
set the following properties:
Property
Value
id
@+id/zipCodeEntry
layout_marginLeft
10dp
layout_marginBottom
10dp
width
165dp
11. From the Toolbox, drag a Button onto the RelativeLayout control and position it to the right of the zipCodeEntry
control. Then set these properties:
Property
Value
id
@+id/weatherBtn
text
Get Weather
layout_marginLeft
20dp
layout_alignBottom
@id/zipCodeEntry
21-11-2016 21:56
10 of 19
Property
Value
width
165dp
https://msdn.microsoft.com/en-us/library/dn879698(d=printer).aspx
XML
<Button
android:text="Get Weather"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@id/zipCodeEntry"
android:id="@+id/weatherBtn"
android:layout_marginLeft="20dp"
android:layout_alignBottom="@id/zipCodeEntry"
android:width="165dp" />
12. You now have enough experience to build a basic UI by using the Android designer. You can also build a UI by
adding markup directly to the .asxml file of the page. To build the rest of the UI that way, switch to Source view in
the designer, then past the following markup beneath the </RelativeLayout> tag (yes, that's beneath the
tag...these elements are not contained in the ReleativeLayout).
XML
<TextView
android:text="Location"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/locationLabel"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp" />
<TextView
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/locationText"
android:layout_marginLeft="20dp"
android:layout_marginBottom="10dp" />
<TextView
android:text="Temperature"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tempLabel"
android:layout_marginLeft="10dp" />
<TextView
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/tempText"
android:layout_marginBottom="10dp"
android:layout_marginLeft="20dp" />
<TextView
android:text="Wind Speed"
android:textAppearance="?android:attr/textAppearanceSmall"
21-11-2016 21:56
11 of 19
https://msdn.microsoft.com/en-us/library/dn879698(d=printer).aspx
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/windLabel"
android:layout_marginLeft="10dp" />
<TextView
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/windText"
android:layout_marginBottom="10dp"
android:layout_marginLeft="20dp" />
<TextView
android:text="Humidity"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/humidtyLabel"
android:layout_marginLeft="10dp" />
<TextView
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/humidityText"
android:layout_marginBottom="10dp"
android:layout_marginLeft="20dp" />
<TextView
android:text="Visibility"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/visibilityLabel"
android:layout_marginLeft="10dp" />
<TextView
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/visibilityText"
android:layout_marginBottom="10dp"
android:layout_marginLeft="20dp" />
<TextView
android:text="Time of Sunrise"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/sunriseLabel"
android:layout_marginLeft="10dp" />
<TextView
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/sunriseText"
android:layout_marginBottom="10dp"
android:layout_marginLeft="20dp" />
<TextView
android:text="Time of Sunset"
android:textAppearance="?android:attr/textAppearanceSmall"
android:layout_width="match_parent"
android:layout_height="wrap_content"
21-11-2016 21:56
12 of 19
https://msdn.microsoft.com/en-us/library/dn879698(d=printer).aspx
android:id="@+id/sunsetLabel"
android:layout_marginLeft="10dp" />
<TextView
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/sunsetText"
android:layout_marginBottom="10dp"
android:layout_marginLeft="20dp" />
13. Save the file and switch to Design view. Your UI should appear as follows:
14. Open MainActivity.cs and delete the lines in the OnCreate method that refer to the default button that was
removed earlier. The code should look like this when you're done:
21-11-2016 21:56
13 of 19
https://msdn.microsoft.com/en-us/library/dn879698(d=printer).aspx
15. Build the Android project to check your work. Note that building adds control IDs to the Resource.Designer.cs file
so that you can refer to controls by name in code.
System;
Android.App;
Android.Widget;
Android.OS;
namespace WeatherApp.Droid
{
[Activity(Label = "Sample Weather App", MainLauncher = true, Icon =
"@drawable/icon")]
public class MainActivity : Activity
{
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
Button button = FindViewById<Button>(Resource.Id.weatherBtn);
button.Click += Button_Click;
}
private async void Button_Click(object sender, EventArgs e)
{
EditText zipCodeEntry = FindViewById<EditText>
(Resource.Id.zipCodeEntry);
if (!String.IsNullOrEmpty(zipCodeEntry.Text))
{
Weather weather = await Core.GetWeather(zipCodeEntry.Text);
FindViewById<TextView>(Resource.Id.locationText).Text =
weather.Title;
FindViewById<TextView>(Resource.Id.tempText).Text =
weather.Temperature;
FindViewById<TextView>(Resource.Id.windText).Text = weather.Wind;
FindViewById<TextView>(Resource.Id.visibilityText).Text =
weather.Visibility;
FindViewById<TextView>(Resource.Id.humidityText).Text =
weather.Humidity;
FindViewById<TextView>(Resource.Id.sunriseText).Text =
weather.Sunrise;
FindViewById<TextView>(Resource.Id.sunsetText).Text =
21-11-2016 21:56
14 of 19
https://msdn.microsoft.com/en-us/library/dn879698(d=printer).aspx
weather.Sunset;
}
}
}
}
21-11-2016 21:56
15 of 19
https://msdn.microsoft.com/en-us/library/dn879698(d=printer).aspx
Tip
The complete source code for this project is in the mobile-samples repository on GitHub.
21-11-2016 21:56
16 of 19
https://msdn.microsoft.com/en-us/library/dn879698(d=printer).aspx
21-11-2016 21:56
17 of 19
https://msdn.microsoft.com/en-us/library/dn879698(d=printer).aspx
).
This code calls the GetWeather method that you defined in your shared code. This is the same method that you
called in your Android app. This code also shows data retrieved from that method in the UI controls of your app.
5. In MainPage.xaml.cs, which is open, delete all the code inside the OnNavigatedTo method. This code simply
handled the default button that was removed when we replaced the contents of MainPage.xaml.
21-11-2016 21:56
18 of 19
https://msdn.microsoft.com/en-us/library/dn879698(d=printer).aspx
Tip
The complete source code for this project is in the mobile-samples repository on GitHub.
Next steps
Add UI for iOS to the solution
Extend this sample by adding native UI for iOS. For this youll need to connect to a Mac on your local network that has
Xcode and Xamarin installed. Once you do, you can use the iOS designer directly in Visual Studio. See the mobile-samples
repository on GitHub for a completed app.
21-11-2016 21:56
19 of 19
https://msdn.microsoft.com/en-us/library/dn879698(d=printer).aspx
Also refer to the Hello, iOS (xamarin.com) walkthrough. Note that on this page, be sure that "Visual Studio" is selected in
the upper right corner of pages on xamarin.com so that the correct set of instructions appear.
Add platform-specific code in a shared project
Shared code in a PCL is platform-neutral, because the PCL is compiled once and included in each platform-specific app
package. If you want to write shared code that uses conditional compilation to isolate platform-specific code, you can use
a shared project. For more details, see ode Sharing Options (xamarin.com).
See Also
Xamarin Developer site
Windows Dev Center
Swift and C# Quick Reference Poster
2016 Microsoft
21-11-2016 21:56