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:
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.
|
Create an Android project
Add a Windows Phone project
Create a shared project
Perform some minor tweaks to the solution
Run your apps to make sure that they work
Run the Android app
Tip |
---|
As an alternative to the Visual Studio Emulator for Android, you can also try using theXamarin Android Player.
|
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
{
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
Tip |
---|
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
|
Tip |
---|
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
|
<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.
- 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.
- Rename the project to WeatherApp (Android)
- 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.
- 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.
- Open the shortcut menu for the WeatherApp (Android) project, and then choose Add>Reference.
- In the dialog box that appears, select the Shared project, and then choose the OK button.
- Repeat this process for the Windows Phone project.
- 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.
- Open the shortcut menu for the WeatherApp (Android) project, and then choose Add>Reference.
- 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.
- 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.
- Stop the debugger.
- Open the shortcut menu for the WeatherAppWindows (Windows Phone 8.1) project, and then choose Set as Startup Project.
- On the Standard toolbar, select one of the emulator options.
- 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.
- 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.
- 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.
- 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.
- Add another class to the Shared project and name the file DataService.
- Open the DataService.cs file and add the following statements at the top:
- Replace the class declaration with the following code:This code shows one way to process JSON data from a service.
- 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.
- Open Core.cs and add the following statement at the top:
- 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.
- 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.
- Delete the default button that appears in the designer.
- From the Toolbox, drag a RelativeLayout control onto the designer.You can use this control as a parent container for other controls.
- From the Toolbox, drag a TextView control onto the RelativeLayout control.
- In the Properties window, set these properties:
- From the Toolbox, drag a Number control onto the RelativeLayout and position it next to the Zip Code label.
- In the Properties window, set these properties:
- Choose the button next to the background property.
- In the Framework Resources tab, choose the background_light color and then choose theOK button.
- From the Toolbox, drag a Button onto the RelativeLayout control and position it next to the zip code edit box.
- In the Properties window, set these properties:
- 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.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.
- At the bottom of the designer, choose the Source tab.
- In Source view, paste the following markup beneath the
Open the Design view again.
Your UI should appear as follows:
Build the solution.
This adds control IDs to the Resource.Designer.cs file so that you can refer to controls by name in code.
- Open the MainActivity.cs file of the WeatherApp project in the code editor.
- Add the following statement to the top of the file
- 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.
- In Solution Explorer, set the WeatherApp project as the startup project.
- Start the app by pressing the F5 key.
- 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.
Now we’ll design the user interface, connect it to your shared code, and then run the app.
- 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.
- From the Toolbox, drag a TextBlock onto the designer and position it near the top of the page.
- In the Properties window, expand the Common section of properties, and set the Textproperty to Weather App.
- Expand the Text section, and set the font size to 30 pt.
- From the Toolbox, drag a TextBlock to the designer and position it beneath the Weather App title.
- Set the Text property to Zip Code and the font size to 15 pt.
- From the Toolbox, drag a TextBox to the designer and position it beside the Zip Codelabel.
- Set the Name property to ZipCodeEdit
- Clear the Text property so that no text appears in the text box.
- On the designer, drag the edge of the textbox to widen its size.It needs to be wide enough to show five digits.
- In the Properties windows, expand the Brush section, and then select the Foregroundproperty. Choose an interesting color like purple.When users enter a zip code, the text will appear in this color.
- From the Toolbox, drag a button to the designer and position it beside the text box.
- In the Properties window, expand the Common section, and then set the Content property to Get Weather.
- Set the Name property to GetWeatherButton.
- 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.
- In XAML view, paste the following markup beneath the button.In the design view, your UI should appear as follows:
- In the designer, select the Get Weather button.
- In the Properties window, choose the event handler button ().This icon appears in the top corner of the Properties window.
- 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.
- 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.
- Add the following statement to the top of the file
- In Solution Explorer, set the WeatherAppWindows (WinPhone) project as the startup project.
- Start the app by pressing the F5 key.
- 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.
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
Post A Comment: