Once you've done the steps in Setup and install and Verify your Xamarin environment, this walkthrough helps you build a basic Xamarin app with native UI layers on Android and Windows Phone:
Xamarin app on Android and Windows Phone
System_CAPS_noteNote
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.
First, set up your solution
Create an Android project
Add a Windows Phone project
Create a shared project
Perform some minor tweaks to the solution
Newtonsoft.JSON Nuget package
Run your apps to make sure that they work
Run the Android app
System_CAPS_tipTip
As an alternative to the Visual Studio Emulator for Android, you can also try using theXamarin Android Player.
Run the Windows app
List of Windows Phone Emulator images
Write code that you can share between your apps
C#
public class Weather
{
public string Title { get; set; }
public string Temperature { get; set; }
public string Wind { get; set; }
public string Humidity { get; set; }
public string Visibility { get; set; }
public string Sunrise { get; set; }
public string Sunset { get; set; }
}
C#
using System.Threading.Tasks;
using System.Net;
using System.IO;
using Newtonsoft.Json;
C#
public class DataService
{
public static async Task<dynamic> getDataFromService(string queryString)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(queryString);
var response = await request.GetResponseAsync().ConfigureAwait(false);
var stream = response.GetResponseStream();
var streamReader = new StreamReader(stream);
string responseText = streamReader.ReadToEnd();
dynamic data = JsonConvert.DeserializeObject(responseText);
return data;
}
}
C#
using System.Threading.Tasks;
C#
public class Core
{
public static async Task GetWeather(string zipCode)
{
string queryString =
"https://query.yahooapis.com/v1/public/yql?q=select+*+from+weather.forecast+where+location=" +
zipCode + "&format=json";
dynamic results = await DataService.getDataFromService(queryString).ConfigureAwait(false);
dynamic weatherOverview = results["query"]["results"]["channel"];
if ((string)weatherOverview["description"] != "Yahoo! Weather Error")
{
Weather weather = new Weather();
weather.Title = (string)weatherOverview["description"];
dynamic wind = weatherOverview["wind"];
weather.Temperature = (string)wind["chill"];
weather.Wind = (string)wind["speed"];
dynamic atmosphere = weatherOverview["atmosphere"];
weather.Humidity = (string)atmosphere["humidity"];
weather.Visibility = (string)atmosphere["visibility"];
dynamic astronomy = weatherOverview["astronomy"];
weather.Sunrise = (string)astronomy["sunrise"];
weather.Sunset = (string)astronomy["sunset"];
return weather;
}
else
{
return null;
}
}
}
Design for Android
Design the look and feel of your app
System_CAPS_tipTip
There are a lot of 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.
Property
Value
text
Zip Code:
id
@+id/ZipCodeLabel
layout_centerVertical
true
layout_marginLeft
10dp
textSize
20sp
System_CAPS_tipTip
Notice that many properties don’t 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.
Property
Value
id
@+id/ZipCodeEdit
layout_centerVertical
true
layout_marginLeft
10dp
textSize
20sp
layout_width
100sp
textColor
#9933FF

Property
Value
id
@+id/GetWeatherButton
text
Get Weather
layout_marginLeft
10dp
textSize
20sp
XML
<TextView
android:text="Current Weather"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/ResultsTitle"
android:textColor="#FFFF4D"
android:visibility="visible"
android:layout_marginLeft="25px" />
<TableLayout
android:minWidth="25px"
android:minHeight="25px"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/ResultsTable"
android:padding="10dp"
android:visibility="visible">
<TableRow
android:id="@+id/tableRow1">
<TextView
android:text="Temp:"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_column="0"
android:id="@+id/textView21" />
<TextView
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_column="1"
android:id="@+id/TempText"
android:text="70"
android:textColor="#FFFF4D"
android:layout_height="wrap_content" />
<TextView
android:text="F"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_column="2"
android:id="@+id/textView26" />
</TableRow>
<TableRow
android:id="@+id/tableRow2">
<TextView
android:text="Wind:"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_column="0"
android:id="@+id/textView22" />
<TextView
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_column="1"
android:id="@+id/WindText"
android:text="10"
android:textColor="#FFFF4D" />
<TextView
android:text="mph"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_column="2"
android:id="@+id/textView27"
android:layout_height="wrap_content" />
</TableRow>
<TableRow
android:id="@+id/tableRow3">
<TextView
android:text="Humidity:"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_column="0"
android:id="@+id/textView23"
android:layout_width="107.0dp" />
<TextView
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_column="1"
android:id="@+id/HumidityText"
android:text="70"
android:textColor="#FFFF4D"
android:layout_height="wrap_content" />
<TextView
android:text="%"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_column="2"
android:id="@+id/textView28" />
</TableRow>
<TableRow
android:id="@+id/tableRow4">
<TextView
android:text="Visibility:"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_column="0"
android:id="@+id/textView34" />
<TextView
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_column="1"
android:id="@+id/VisibilityText"
android:text="10"
android:textColor="#FFFF4D"
android:layout_height="wrap_content" />
<TextView
android:text="miles"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_column="2"
android:id="@+id/textView50" />
</TableRow>
<TableRow
android:id="@+id/tableRow5">
<TextView
android:text="Sunrise:"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_column="0"
android:id="@+id/textView40" />
<TextView
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_column="1"
android:id="@+id/SunriseText"
android:text="7:46 am"
android:textColor="#FFFF4D" />
</TableRow>
<TableRow
android:id="@+id/tableRow6">
<TextView
android:text="Sunset:"
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_column="0"
android:id="@+id/textView46" />
<TextView
android:textAppearance="?android:attr/textAppearanceMedium"
android:layout_column="1"
android:id="@+id/SunsetText"
android:text="5:58 PM"
android:textColor="#FFFF4D" />
</TableRow>
</TableLayout>
Consume your shared code
C#
using Shared;
C#
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
Button button = FindViewById
You'll do these things to build it:

Create an Android, Windows Phone, and a shared project, and then make a few tweaks to the solution.
  1. In Visual Studio, create a new Blank App (Android) project and name it WeatherApp.
    You can find this template under Visual C# >Android in the New Project dialog box.
    If it’s not there, you might have to install Xamarin or enable the Visual Studio 2015 feature, seeSetup and install.
  2. Rename the project to WeatherApp (Android)
  1. Add a Blank App (Windows Phone) project to the solution and name itWeatherAppWindows.
    You can find this template under Visual C# >Windows > Windows 8 >Windows Phone in the New Project dialog box.
    If it’s not there, you might have to install the tools for developing Windows 8.1 apps. You can do that by opening Programs and Features and modifying your Visual Studio setup.
  1. Add a Shared Project to the solution and name it Shared.
    You can find this template under Visual C# >Windows in the New Project dialog box.
  2. Open the shortcut menu for the WeatherApp (Android) project, and then choose Add>Reference.
  3. In the dialog box that appears, select the Shared project, and then choose the OK button.
    Shared project reference
  4. Repeat this process for the Windows Phone project.
  1. Choose Tools > NuGet Package Manager > Manage NuGet Packages for Solution and add the Newtonsoft.Json NuGet package to your solution.
    You’ll use classes in this package to process information that you’ll retrieve from a weather service.
  2. Open the shortcut menu for the WeatherApp (Android) project, and then choose Add>Reference.
  3. In the Reference Manager dialog box, add a reference to the Microsoft.CSharp assembly.

You’ve configured the solution. Now you’re ready to run your apps and make sure that they work.

  1. In Visual Studio, choose Debug>Start Debugging.
    The Visual Studio Emulator for Android starts.
    The app appears in the Android emulator. The app shows a button that contains the textHello World, Click Me!. This means that the app works.
  2. Stop the debugger.

  1. Open the shortcut menu for the WeatherAppWindows (Windows Phone 8.1) project, and then choose Set as Startup Project.
  2. On the Standard toolbar, select one of the emulator options.
  3. Press the F5 key on your keyboard to run the app in the Windows Phone emulator.
    Your app runs in the emulator but you won’t see any controls because the Blank App (Windows Phone) template has no UI by default.
  4. Stop the debugger.

Add code that you want to share between your apps to the Shared project. A shared project is basically a container for code that runs on both platforms. Anything you add to this project is automatically included in both the Android and the Windows Phone project.
  1. Add a class to the Shared project and name it Weather.
    On the shortcut menu for the Shared project, choose Add > New Item. Then, in the Add New Item dialog box, select the Class item, and name it Weather.
  2. Open the Weather.cs file and replace the class declaration with the following code:
    You’ll use this class to store data from a weather service.
  3. Add another class to the Shared project and name the file DataService.
  4. Open the DataService.cs file and add the following statements at the top:
  5. Replace the class declaration with the following code:
    This code shows one way to process JSON data from a service.
  6. Add another class to the Shared project and name it Core.
    The name Core is arbitrary. This class is just a place to put shared business logic. In this case, logic that forms a query string by using zip code, calls the weather service, and then populates an instance of the Weather class.
  7. Open Core.cs and add the following statement at the top:
  8. Replace the class declaration with the following code:

Now, we’ll design the user interface, connect it to your shared code, and then run the app.

  1. In Solution Explorer, expand the WeatherApp (Android)>Resources>layout folder, select the Main.axml file, and then press the ENTER key.
    Main.axml opens in the visual designer. If a Java-related error appears, see this blog post.
  2. Delete the default button that appears in the designer.
  3. From the Toolbox, drag a RelativeLayout control onto the designer.
    You can use this control as a parent container for other controls.
  4. From the Toolbox, drag a TextView control onto the RelativeLayout control.
  5. In the Properties window, set these properties:
  6. From the Toolbox, drag a Number control onto the RelativeLayout and position it next to the Zip Code label.
    Number dragged onto the designer
  7. In the Properties window, set these properties:
  8. Choose the button next to the background property.
  9. In the Framework Resources tab, choose the background_light color and then choose theOK button.
  10. From the Toolbox, drag a Button onto the RelativeLayout control and position it next to the zip code edit box.
  11. In the Properties window, set these properties:
  12. Select the zip code edit box. Resize it to match the height of the Get Weather button by selecting and dragging the small circle that appears beneath the edit box.
    Edit box being resized in the designer
    You now have enough experience to build a basic UI by using the Android designer. But you can also build a UI by adding tags directly to the .asxml file of the page. Let’s build the rest of the UI by doing that.
  13. At the bottom of the designer, choose the Source tab.
    Source view tab
  14. In Source view, paste the following markup beneath the 
 tag.
  • Open the Design view again.
    Your UI should appear as follows:
    UI for Android app
  • Build the solution.
    This adds control IDs to the Resource.Designer.cs file so that you can refer to controls by name in code.
    1. Open the MainActivity.cs file of the WeatherApp project in the code editor.
    2. Add the following statement to the top of the file
    3. Replace the OnCreate method with this code.
      This code calls the GetWeather method that you defined in your shared code. Then, in the UI of the app, it shows the data that is retrieved from that method.

    1. In Solution Explorer, set the WeatherApp project as the startup project.
    2. Start the app by pressing the F5 key.
    3. In the Android emulator, type a valid United States zip code into the edit box (for example: 98052), and then press the Get Weather button.
      Weather data for that region appears in the controls.
      Weather app for Android and Windows Phone

    Now we’ll design the user interface, connect it to your shared code, and then run the app.

    1. In Solution Explorer, select the MainPage.xaml file of the WeatherAppWindows (WinPhone) project, and then press the ENTER key.
      The MainPage.xaml file opens in the designer.
    2. From the Toolbox, drag a TextBlock onto the designer and position it near the top of the page.
    3. In the Properties window, expand the Common section of properties, and set the Textproperty to Weather App.
      Text property of the title
    4. Expand the Text section, and set the font size to 30 pt.
    5. From the Toolbox, drag a TextBlock to the designer and position it beneath the Weather App title.
    6. Set the Text property to Zip Code and the font size to 15 pt.
    7. From the Toolbox, drag a TextBox to the designer and position it beside the Zip Codelabel.
    8. Set the Name property to ZipCodeEdit
    9. Clear the Text property so that no text appears in the text box.
    10. On the designer, drag the edge of the textbox to widen its size.
      It needs to be wide enough to show five digits.
    11. In the Properties windows, expand the Brush section, and then select the Foregroundproperty. Choose an interesting color like purple.
      Foreground color property in the Properties Window
      When users enter a zip code, the text will appear in this color.
    12. From the Toolbox, drag a button to the designer and position it beside the text box.
    13. In the Properties window, expand the Common section, and then set the Content property to Get Weather.
    14. Set the Name property to GetWeatherButton.
      Name property of a control
    15. You now have enough experience to build a basic UI by using the Windows designer. But you can also build a UI by adding tags directly to the xaml file of the page. Let’s build the rest of the UI by doing that.
    16. In XAML view, paste the following markup beneath the button.
      In the design view, your UI should appear as follows:
      Windows Phone app UI

    1. In the designer, select the Get Weather button.
    2. In the Properties window, choose the event handler button (Visual Studio Event Handlers icon).
      This icon appears in the top corner of the Properties window.
    3. Next to the Click event, type GetWeatherButton_Click, and then press the ENTER key.
      This generates an event handler named GetWeatherButton_Click. The code editor opens and places your curser inside of the event handler code block.
    4. Replace that event handler with the following code.
      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. Add the following statement to the top of the file

    1. In Solution Explorer, set the WeatherAppWindows (WinPhone) project as the startup project.
    2. Start the app by pressing the F5 key.
    3. In the Windows Phone emulator, type a valid United States zip code into the edit box (for example: 98052), and then press the Get Weather button.
      Weather data for that region appears in the controls.
      Windows version of the running app

    Congratulations on building your first cross-platform mobile app. Although this topic gets you started, there’s so much more to learn.
    Here are a few ideas about what you can explore next on your journey to build beautiful native mobile apps by using C# and Visual Studio.
    Add an iOS project to the solution
    Extend this sample by adding a project for iOS. To build and run that app, you’ll have to connect to a Mac on your local network that has Xcode and Xamarin installed.
    See Hello, iOS (xamarin.com). NOTE: 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 the shared project
    Not all shared code has to run in both platforms. Use conditional compilation constants to isolate platform-specific code. You can reduce the number of constants that appear in a file by creating partial classes. Factor out platform-specific code into a separate file and then apply a compilation constant to that file.
    Consider other ways to share your code
    You can also share code by using a Portable Class Library. Learn about the differences between a Portable Class Library and a shared project and choose an approach that makes the most sense for your project.
    Design one user interface that runs on all platforms
    If your UI uses common patterns such as list and detail views, consider using Xamarin.Forms to implement it. Xamarin.Forms uses XAML so you can declaratively bind properties and methods to your UI. This can be very attractive if your goal is to reduce the amount of code in your UI layer.
    reference:msdn.microsoft.com
    Axact

    Author

    My name is Dave, Am a cool IT Geek, computer analyst and a tutor. I do alot of computer stuffs like programming, web development, blogging, data administrator, computer security and lots more. Feel free to contact me if want more informations and tutorials.

    Post A Comment: