Getting Started with Windows 8 Apps for Android Developers

If you develop Android apps and want to also develop apps for Windows 8, this is a great place to start. We'll show you how to use Microsoft development tools like Microsoft Visual Studio and Microsoft programming languages like C#. You'll learn some concepts you need to know to develop apps for new Windows UI in Windows 8. We call these apps Windows Store apps.

(sponsored)

Windows 8 introduced a new platform for creating engaging apps. Because Windows Store apps provide lots of unique features, a straight port of your Android app will likely prevent you and your users from using these features. So don't just port your app. Reimagine your app, and take advantage of features like the app bar, Semantic Zoom, the search and Share contracts, the file picker, charms, live tiles, and toast notifications.

To get started with these walkthroughs, you'll need a computer with both Windows 8.1 and Microsoft Visual Studio 2013 installed. You can download these from the Windows 8.1 for Developers page.

The following video provides a brief comparison of Eclipse and Visual Studio.

Getting Windows 8.1 and the app development tools

To do these walkthroughs, you'll need a computer with Windows 8.1 and Visual Studio 2013 installed. To get them, go to the Windows 8.1 for Developers page.

After you start Visual Studio 2013 for the first time, it will ask you to get a developer license. Just follow the on-screen directions to get one. This license lets you create and test Windows Store apps on your local development computer before you submit those apps to the Windows Store.

For comparison, before you start Android app development, you need to install the Java Runtime Environment (JRE), then the Eclipse IDE, the Android software development kit (SDK) Tools, and the Android Developer Tools (ADT) plugin.

Creating a project

Unlike Eclipse, which is designed as a general-purpose integrated development environment (IDE), Visual Studio is targeted at, and designed for, developing Windows Store apps.

Watch this brief video for a comparison of Eclipse and Visual Studio.

In this walkthrough, we'll introduce you to the basics of Visual Studio and compare them to similar basics in Eclipse. Each time you create an app, you'll follow steps similar to these.

For comparison, when you start Eclipse for Android app development, you create a new project by tapping File > New > Android Application Project, as shown in the following figure.

Eclipse New Android Application Project menu command

After you create a new Android project in Eclipse, you can select the activity type, as shown in the following figure.

Eclipse Create Activity page

When you start Microsoft Visual Studio, you'll see the Start Page, as shown in the following figure.

Visual Studio start screen

To create a new app, start by creating a new project by doing one of the following:

  • In the Start area, tap New Project.
  • Tap the File menu, and then tap New Project.

There are several project templates to choose from, as shown in the following figure.

Visual Studio new project dialog box

Android Tip

The Windows Store project template in Visual Studio is similar to the Android Application Project template that is added to Eclipse after you install the Android Developer Tools (ADT) Plugin.

For this walkthrough, tap Visual C#, and then tap Blank App (XAML). In the Name box, type "MyApp", and then tap OK. Visual Studio creates and then displays your first project. Now you can begin to design your app and add code to it.

Android Tip

The Location box in the Visual Studio New Project dialog box is similar to a workspace that is used by Eclipse.

Unlike an Android Eclipse project where you create one activity at a time, Visual Studio includes project templates that create apps with multiple pages and navigation between those pages. The Blank App template, on the other hand, creates an app with only one page. Don't worry, though—we'll add a second page and navigation later in this article.

Top

Choosing a programming language

Before we go any further, you should know about the programming languages that you can choose from when you develop Windows Store apps. Although the walkthroughs in this article use C#, you can develop Windows Store apps using several programming languages. By contrast, you use only Java to develop Android apps.

You can develop Windows Store apps using C#, C++, Microsoft Visual Basic, or JavaScript. JavaScript uses HTML5 markup for UI layout. The rest of the languages use a markup language called Extensible Application Markup Language (XAML), which you'll learn about in walkthroughs later in this article.

Although we're focusing on C# in this article, the other languages offer unique benefits, which you may want to explore. For example, if your app's performance is a primary concern, especially for intensive graphics, then C++ might be the right choice. The Microsoft .NET version of Visual Basic is great for Visual Basic app developers. JavaScript with HTML5 is great for those coming from a web development background. For more info, see one of the following:

Note For apps that use 3D graphics, the OpenGL and OpenGL ES standards are not available for Windows Store apps. However, you can use Microsoft DirectX—with C++. Like OpenGL ES 2.0, DirectX 11.1 supports a programmable pipeline and uses a Microsoft High Level Shader Language (HLSL) that is comparable to the OpenGL Shading Language (GLSL). To learn more about DirectX, see the following:

As an Android developer, you're used to Java. We think that C# is the closest Microsoft programming language to Java, so this article's info and walkthroughs focus on that language. To learn more about C#, see the following:

Following is a class written in Java and C#. The Java version is shown first, followed by the C# version. You'll see that the structure is very similar, making it fairly easy to get started with C#. In this example, you'll also see that there are small differences in casing and documentation syntax. Finally, you'll see that C# classes can have explicit properties instead of using conventional getter and setter methods as in Java.

package com.example.MyApp;

// Java class definition.
/** 
 * The Counter class shows key aspects of a Java class.
 */
public class Counter {
    private int count; // Private variables are not visible outside.

    public Counter() 
    {
        count = 0; // Initialize the local variable.
    }

    public int getValue()  // Getter for the local variable.
    {
        return count;      
    }

    public void setValue(int value) // Setter for the local variable.
    {
        count = value;         
    }	

    public int increment(int delta)
    {
    	   // Add the delta to the local count, and then return.
    	   count += delta;
        return count;
    }        

    public int increment()
    {
        return increment(1);
    }    
}

// Java usage.
import com.example.myapp.Counter;

Counter myCounter = new Counter();
int count = myCounter.getValue();
myCounter.setValue(5);
count = myCounter.increment();


// C# class definition.
namespace MyApp
{
    public class Counter
    {
        private int count; // Private variable not visible outside of the class.

        public Counter()
        {
            count = 0; // Initialize the local variable.
        }

        public int Value // Getter for the local variable.
        {
            get
            {
                return count;
            }
            set
            {
                count = value;
            }
        }

        /// <summary>
        /// Increments the counter by the delta.
        /// </summary>
        /// <param name="delta">delta</param>
        /// <returns>Returns the resulting counter.</returns>
        public int Increment(int delta)
        {
            // Add the delta to the local count, and then return.
            count += delta;
            return count;
        }

        public int Increment()
        {
            return Increment(1);
        }
    }

// C# usage.
using MyApp;

Counter myCounter = new Counter();
int count = myCounter.Value;
myCounter.Value = 5;
count = myCounter.Increment();


Top

 

Getting around in Visual Studio

Let's now return to the MyApp project that you created earlier and show you how to find your way around the Visual Studio IDE.

Android developers using Eclipse should be familiar with the default view in the following figure, where you have source files in the left pane, the editor (either the UI or code) in the center pane, and controls and their properties in the right pane, as shown in the following figure.

Eclipse integrated development environment

Visual Studio is similar, although the default view has the controls on the left side in the Toolbox. The source files are in the Solution Explorer on the right side, and properties are in Properties on the right side. This layout is shown in the following figure.

Visual Studio development environment

Android Tips

Solution Explorer in Visual Studio is similar to Package Explorer in Eclipse.

In Solution Explorer, the Package.appxmanifest file is similar to the AndroidManifest.xml file that is used in Android apps.

In Solution Explorer, the items in the Assets directory are similar to the items in the \res\drawable-*\ directories of Android projects.

You can rearrange the panes in Visual Studio if you want your source files on the left side and controls on the right side. Or like Eclipse, you can choose the windows you need and arrange them according to your preference. For example, to move the Toolbox from the left side of the screen to the right side, press and hold the Toolbox pane's title bar, begin dragging it, and then drop it on the far right drop target that appears in the middle of the screen. Visual Studio displays a shaded box to let you know where the Toolbox will be docked after you drop it there.

To make your IDE look like the previous figure, do this:

  1. In Solution Explorer, press and hold MainPage.xaml to open it.
  2. On the left side, tap Toolbox to display it. Then, in the Toolbox pane's title bar, tap the pushpin icon to pin it, as shown in the following figure.

Pinning the Toolbox in Visual Studio

Top

Adding controls, setting their properties, and responding to events

Let's now add some controls to your MyApp project. We'll then change some of the controls' properties, and then we'll write some code to respond to one of the control's events.

To add controls in Eclipse, you open up the activity XML file in Graphical Layout and then add controls, like Button, EditText, and TextView, as shown in the following figure. In Visual Studio, .xaml files are similar to Android layout .xml files.

Eclipse Graphical Layout editor

Let's do something similar in Visual Studio. In the Toolbox, press and hold the TextBox control, and then drop it onto the MainPage.xaml file's design surface. Do the same with the Button control, placing it below the TextBox control. Finally, do the same with the TextBlock control, placing it below the Button control, as shown in the following figure.

Visual Studio MainPage Design view

Similar to Android layout .xml files in Eclipse, in Visual Studio, .xaml files display UI layout details in a rich, declarative language. For more info about XAML, see XAML overview. Everything that is displayed in the Design pane is defined in the XAML pane. The XAML pane allows for finer control where necessary, and as you learn more about it, you can develop code faster. For now however, let's focus on just the Design pane and Properties.

Visual Studio Tips

The *.xaml.cs file that is associated with a *.xaml file is called the code-behind file.

When you open a *.xaml file, you'll see a split Design/XAML view by default. By default, the top view contains a visual designer, and the bottom view contains the markup that's generated by the designer. If you want to modify the XAML directly and you need more screen space in the XAML view, either click the up/down arrow button between the Design and XAML views to show more of the XAML view, or click the double-chevron button between the Design and XAML views to minimize the Design view completely.

Android Tip

The relationship between *.xaml and *.xaml.cs files is similar to the relationship between layouts and activities in Android development. When you create a generic Android app in Eclipse, you'll see an activity_main.xml file in the project's \res\layout\ directory. This is where you define the UI for your Android app. You also see a MainActivity.java file in the project's \src\ directory. This is where you write the code that goes along with the app's UI. In our project in Visual Studio, the MainPage.xaml file corresponds to the activity_main.xml in Eclipse, and the MainPage.xaml.cs file in Visual Studio corresponds to the MainActivity.java file in Eclipse.

Let's now change the button's contents and name. To change the button's contents in Eclipse, in the button's properties pane, you change the value of the Text property, as shown in the following figure.

Eclipse Resource Chooser

In Visual Studio you do something similar. In the Design pane, tap the Button control to give it the focus. Then, to change the button's contents, in the Properties pane, change the Content box's value from "Button" to "Say Hello". Next, to change the Button control's name, change the Name box's value from "<No Name>" to "sayHelloButton", as shown in the following figure.

Visual Studio setting button properties

Let's now change the TextBlock control's name and contents. Tap the TextBlock control to give it the focus. In the Properties pane, change the Text box's value from "TextBlock" to "Hello". Then change the Name box's value from "<No Name>" to "helloMessage", as shown in the following figure.

Visual Studio setting text block properties

Next, let's change the TextBox control's name and contents. Tap the TextBox control to give it the focus. In the Properties pane, change the Content box's value from "TextBox" to "Enter your name". Then change the Name box's value from "<No Name>" to "nameField".

Now let's write some code to change the TextBlock control's contents to greet the user after the user types his or her name and then taps the button.

In Eclipse, you would associate an event's behavior with a control by associating that code with the control, similar to the following figure and code.

Eclipse setting button properties

<Button
    android:id="@+id/sayHelloButton"
    android:layout_width="147dp"
    android:layout_height="wrap_content"
    android:layout_marginTop="10dip"
    android:onClick="displayMessage"
    android:text="@string/button_title" />


Visual Studio is similar. At the top right of Properties is a lightning bolt button. This is where the events that are associated with the selected control are listed, as shown in the following figure.

Visual Studio setting button event handler

To add code for the button's click event, in the Design pane, first tap the button. Then tap the lightning bolt button in Properties, and press and hold the box next to the Click label. Visual Studio adds the text "sayHelloButton_Click" to the Click box and then adds and displays the corresponding event handler in the MainPage.xaml.cs file, as shown in the following code.

private void sayHelloButton_Click(object sender, RoutedEventArgs e)
{

}

Let's now add some code to this event handler, as follows.

private void sayHelloButton_Click(object sender, RoutedEventArgs e)
{
    helloMessage.Text = "Hello " + nameField.Text + "!";
}

Following is some similar code that you would write in Eclipse.

/** Called when the user clicks the button. */
public void displayMessage(View view) {
    EditText nameField = (EditText) findViewById(R.id.nameField);
    String name = nameField.getText().toString();
    TextView helloMessage = (TextView) findViewById(R.id.messageView);
    helloMessage.setText("Hello "+name+ "!");		
}


Finally, to run the app, in Visual Studio, tap the Debug menu, and then tap Start Debugging or Start Without Debugging. After the app starts, in the Enter your name box, type "Phil". Tap the Say Hello button, and see the label's contents change from "Hello" to "Hello Phil!", as shown in the following figure.

Running the app displays Hello and the user's name

To quit the app, in Visual Studio, tap the Debug menu, and then tap Stop Debugging.

Visual Studio Tip

You can run the app in three modes: on the local machine, in a simulator, or on a remote machine. When you run the app on the local machine, the app runs in full-screen mode on the same machine as Visual Studio. You can interact with the app by using the mouse, or with touch if it's available on the machine. The simulator is a desktop app that also runs on the local machine and simulates touch and rotation events. It is particularly useful if the local machine doesn't support these events. It can also be useful for debugging the app and viewing its code at the same time. Lastly, you can run the app on a machine connected over a network. This is especially useful if that machine support touch events, geolocation, or physical orientation sensors.

To change the app's run mode, on the Visual Studio Standard toolbar, tap the down arrow next to either Local Machine, Simulator, or Remote Machine, and select a different mode. To run the app in that mode, either tap the start arrow next to the mode you selected; or tap the Debug menu, and then tap Start Debugging or Start Without Debugging.

Top

Common controls list

In the previous section, you worked with only three controls. Of course, there are many more controls that are available to you. Here are some common ones. The Android controls are listed in alphabetical order, next to their equivalent Windows Store app controls.

Android control (class)Equivalent Windows Store app control

Progress bar (ProgressBar)

ProgressRing, ProgressBar

See also Quickstart: adding progress controls

Advertising (ADView, ADRequest)

See Microsoft Advertising SDK

Button (Button)

Button

See also Quickstart: Adding button controls

Date picker (DatePicker)

DatePicker (available only for Windows Store apps using C#, C++, and Visual Basic)

DatePicker (available only for Windows Store apps using JavaScript and HTML)

Image (ImageView)

Image

See also Quickstart: Image and ImageBrush

Read-only text (TextView)

TextBlock

See also Quickstart: displaying text

Map view (MapFragment)

See Bing Maps for Windows Store apps

Navigation (Activity) and navigation helpers (NavUtils, TaskStackBuilder)

Frame

See also Quickstart: Navigating between pages

Page (Activity)

Page

See also Quickstart: Navigating between pages

Scrollable list of items (ListView)

ComboBox

See also Adding combo boxes and list boxes

Scrollable layout container (ScrollView)

ScrollViewer

See also XAML scrolling, panning, and zooming sample

Search widget (SearchView)

See Adding search to an app

See also Quickstart: Adding search to an app

Progress bar with draggable thumb (SeekBar)

Slider

See also How to add a slider

Two-state button (RadioButton), two-state box (CheckBox)

ToggleSwitch

See also How to add a toggle switch

Scrollable grid (GridView), row-and-column layout (TableLayout)

GridView

See also Quickstart: adding ListView and GridView controls

Editable text (EditText)

TextBox

See also Quickstart: adding text input and editing controls

Web page view (WebView)

WebView

See also XAML WebView control sample

For even more controls, see Controls list.

Note For a list of controls for Windows Store apps using JavaScript and HTML, see Controls list.

Top

Adding navigation

Android provides three primary ways to manage navigation: temporal navigation through previously visited screens, ancestral and descendent navigation through Intent objects and the startActivity method, and lateral navigation through tabs. Temporal navigation is implemented using an operating system back stack that is managed as the user moves from one activity to another or from one fragment to another. For ancestral and descendent navigation, an activity creates an Intent object and starts a child activity using the startActivity method or through fragments. Lateral navigation takes place using tabs or swipe views.

In Windows 8, navigation should blend into your app's content. This follows from one of the principles of Windows Store app design, "content before chrome". For more info, see Navigation design for Windows Store apps.

With Windows Store apps, one of the ways to manage navigation is with the Frame class. The following walkthrough shows you how to try this out.

Let's further modify the MyApp project that you created earlier to navigate to a new page after a button is clicked, and then show the greeting. Open the MainPage.xaml file if it isn't already visible. Select the TextBlock control that you added earlier, and press Delete to remove it. Also, remove the code that you added to the sayHelloButton_Click event handler.

Let's add a new page: tap the Project menu, and then tap Add New Item. Tap Blank Page as shown in the following figure, and then tap Add.

Adding a new page in Visual Studio

Android Tip

The Page class in Windows Store apps, which represents a page, in similar to the Activity class in Android app development.

Next, add a button to the BlankPage1.xaml file. Let's give the button a back arrow image: in the XAML view, add Style="{StaticResource BackButtonStyle}" to the <Button> element.

Now let's add a TextBlock control underneath the newly added button. Change the name of the TextBlock control to "helloMessage", and change its Text box's value to "Hello". Your result should look like the following figure.

Changing a default button style to a back button style

Android Tip

Unlike Android, there are no system-level "back" or application-level "up" buttons in Windows Store apps. However, developers can implement navigation within their Windows Store apps through similar "back" or "up" functionality. "Back" is represented in this example.

Next, let's add an event handler to the button: in the Properties pane, tap the lightning bolt button, and then press and hold the box next to the Click label. Visual Studio adds the text "Button_Click_1" to the Click box, as shown in the following figure, and then adds and displays the corresponding event handler in the BlankPage1.xaml.cs file.

Setting the back button click event handler

If you return to the BlankPage1.xaml file's XAML view, the <Button> element's XAML code should now look like this. (Line breaks have been added for code readability.)

<Button 
    Content="Button" 
    HorizontalAlignment="Left" 
    Style="{StaticResource BackButtonStyle}"  
    Margin="10,10,0,0" 
    VerticalAlignment="Top" 
    Click="Button_Click_1"
/>

Return to the BlankPage1.xaml.cs file, and add this code to go to the previous page after the user taps the button.

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    // Add the following line of code.    
    Frame.GoBack();
}

Finally, open the MainPage.xaml.cs file and add this code. It opens BlankPage1 after the user taps the button. This line of code is used to navigate to the new page as well as pass the value of the nameField control as a parameter.

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    // Add the following line of code.
    Frame.Navigate(typeof(BlankPage1), nameField.Text);
}

To show the greeting on the new page, open BlankPage1.xaml.cs and add the following code to the OnNavigatedTo method. Whenever the user navigates to a page, the OnNavigatedTo method runs.

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    string name = e.Parameter as string;
    helloMessage.Text = "Hello " + name + "!";
}

Now run the program. Type "Phil", and tap the Say Hello button to go to the second page and show the greeting, as shown in the following figure. Then tap the back-arrow button to return to the previous page.

Clicking the back button displays Hello and the user's name

As you can see, the forward navigation in Windows is similar to Android navigation. In Android, in MainActivity.java, we send an intent to invoke the second page, like this.

public void displayMessage(View view) {
		EditText nameField = (EditText) findViewById(R.id.nameField);
		String name = nameField.getText().toString();		
		Intent intent = new Intent(this, MessageActivity.class);
		intent.putExtra(EXTRA_MESSAGE, name);
		startActivity(intent);		
	}


And in MessageActivity.java, we receive the intent and the data passed with the intent to show the greeting, like this.

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
	   Intent intent = getIntent();
	   String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);		setContentView(R.layout.activity_message);
	   TextView messageView = (TextView) findViewById(R.id.helloMessage);
	   messageView.setText("Hello "+ message+"!");
	   // Show the Up button in the action bar.
	   setupActionBar();
}


However, unlike Windows, Android back stack navigation is provided by ActionBar, and the user doesn't have to do anything.

This walkthrough creates a new instance of BlankPage1 each time you navigate to it. (The previous instance will be freed, or released, automatically by the garbage collector). If you don't want a new instance to be created each time, add the following code to the BlankPage1 class's constructor in the BlankPage1.xaml.cs file. This will enable the NavigationCacheMode behavior.

public BlankPage1()
{
    this.InitializeComponent();
    // Add the following line of code.
    this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;
}

You can also get or set the Frame class's CacheSize property to manage how many pages in the navigation history can be cached.

For more info about navigation, see Quickstart: Navigating between pages and XAML personality animations sample.

Note For info about navigation for Windows Store apps using JavaScript and HTML, see Quickstart: Using single-page navigation.

Android Tip

In a generic Android app, you set the default activity for the app in AndroidManifest.xml. Typically the code looks something like this.

<activity
    android:name="com.example.myfirstapp.MyActivity"
    android:label="@string/app_name" >
      <intent-filter>
          <action android:name="android.intent.action.MAIN" />
          <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
</activity>

If you open the App.xaml.cs file in our Visual Studio project and browse toward the end of the OnLaunched method, you'll see code like this.

if (!rootFrame.Navigate(typeof(MainPage), args.arguments))
{
    throw new Exception("Failed to create initial page");
}

This code displays MainPage.xaml after the app starts.

Top

Adding animations

In Android, you do animations programmatically or with view XML. A view animation allows a view to be transformed (by position, size, rotation, or transparency) to create animations. A property animation allows you to animate property values of view and non-view objects. A drawable animation loads a series of drawable objects, such as bitmaps, one after another to create an animation. Both view animations and drawable animations can be specified using either XML or code. Transition animations allow you to attract user attention by animating when a control enters or leaves or changes one of its properties. Theme animations allow you additional control over timing and order of the animations. For custom animations, you can use storyboard animations by animating a property value of a control.

Animations in Windows Store apps can also be done programmatically, and they can also be done declaratively with XAML. You can use Visual Studio to edit XAML code directly. Also, Visual Studio 2013 comes with a tool called Blend for Microsoft Visual Studio 2013, which edits XAML code for you in the background as you work with animations in a designer. In fact, Blend even allows you to open, design, build, and run complete Visual Studio projects. The following walkthrough lets you try this out.

You can either continue using the MyApp project that you created earlier, or you can create a new project. If you create a new project, you could name it something like "SimpleAnimation". In this project, we're going to move a rectangle, fade it away, and then bring it back into view. Animations in XAML are based on the concept of storyboards. Storyboards use keyframes to animate property changes. There are no implicit animations in Windows Store apps but, as you'll see, animating properties is straightforward.

With your project open, in Solution Explorer, press and hold the project's name, for example, MyApp or SimpleAnimation. Then tap Open in Blend, as shown in the following figure. Visual Studio continues to run in the background.

Open in Blend menu command

After Blend starts, you should see something similar to the following figure.

Blend development environment

Next, tap the Rectangle in the Tools window to select it, and then draw a rectangle in Design View, as shown in the following figure.

Adding a Rectangle to Design View

To make the rectangle green, in the Properties window, in the Brush area, tap the Solid color brush button, tap the Color eyedropper icon, and then tap somewhere in the green band of hues.

To begin animating the rectangle, in the Objects and Timeline window, tap the plus symbol (New) button as shown in the following figure, and then tap OK.

Adding a storyboard

A storyboard appears in the Objects and Timeline window. The Design View display changes to show that Storyboard1 timeline recording is on. To capture the current state of the rectangle, in the Objects and Timeline window, tap the Record Keyframe button just above the yellow arrow, as shown in the following figure.

Recording a keyframe

Now let's move the rectangle and fade it away. To do this, drag the yellow arrow to the 2-second position, and then drag the rectangle slightly to the right. Then, in the Properties window, in the Appearance area, change the Opacity property to 0, as shown in the following figure. To preview the animation, tap the Play button, which is circled in the following figure.

Properties windows and Play button

Next, let's bring the rectangle back into view. In the Objects and Timeline window, tap Storyboard1. Then, in the Properties window, in the Common area, tap AutoReverse, as shown in the following figure.

Selecting a storyboard

Finally, tap the Play button to see what happens.

You can run the project by tapping the Project menu and then tapping Run Project (or just press F5). If you do this, you'll see your green rectangle, but the rectangle won't animate. To start the animation, you'll need to add a line of code to the project. Here's how.

In Blend, tap the File menu, tap Save, and then return to Visual Studio. If Visual Studio displays a dialog box asking whether you want to reload the modified file, tap Yes. Open the MainPage.xaml.cs file, and add the following code.

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    // Add the following line of code.
    Storyboard1.Begin();
}

 

Run the project again, and watch the rectangle animate.

If you open the MainPage.xaml file, in XAML view you'll see the XAML code that Blend added for you as you worked in the designer. In particular, look at the code in the <Storyboard> and <Rectangle> elements. The following code shows an example. Ellipses indicate unrelated code omitted for brevity, and line breaks have been added for code readability.)

...
<Storyboard 
        x:Name="Storyboard1" 
        AutoReverse="True">
    <DoubleAnimationUsingKeyFrames 
            Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateX)"
            Storyboard.TargetName="rectangle">
        <EasingDoubleKeyFrame 
                KeyTime="0" 
                Value="0"/>
        <EasingDoubleKeyFrame 
                KeyTime="0:0:2" 
                Value="185.075"/>
    </DoubleAnimationUsingKeyFrames>
    <DoubleAnimationUsingKeyFrames 
            Storyboard.TargetProperty="(UIElement.RenderTransform).(CompositeTransform.TranslateY)" 
            Storyboard.TargetName="rectangle">
        <EasingDoubleKeyFrame 
                KeyTime="0" 
                Value="0"/>
        <EasingDoubleKeyFrame 
                KeyTime="0:0:2" 
                Value="2.985"/>
    </DoubleAnimationUsingKeyFrames>
    <DoubleAnimationUsingKeyFrames 
            Storyboard.TargetProperty="(UIElement.Opacity)" 
            Storyboard.TargetName="rectangle">
        <EasingDoubleKeyFrame 
                KeyTime="0" 
                Value="1"/>
        <EasingDoubleKeyFrame 
                KeyTime="0:0:2"
                Value="0"/>
    </DoubleAnimationUsingKeyFrames>
</Storyboard>
...
<Rectangle 
        x:Name="rectangle" 
        Fill="#FF00FF63" 
        HorizontalAlignment="Left" 
        Height="122" 
        Margin="151,312,0,0" 
        Stroke="Black" 
        VerticalAlignment="Top" 
        Width="239" 
        RenderTransformOrigin="0.5,0.5">
    <Rectangle.RenderTransform>
        <CompositeTransform/>
    </Rectangle.RenderTransform>
</Rectangle>
...

Compare this to a similar Android animation that animates the location of a square and its opacity. The animation defined in XML has many similarities, as shown in the following code.

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" android:ordering="together" >
    <objectAnimator
        android:propertyName="TranslationX"
        android:duration="2000"
        android:valueFrom="0"
        android:valueTo="400"
        android:repeatCount="1"
        android:repeatMode="reverse"
        android:valueType="floatType"/>
    <objectAnimator
        android:propertyName="TranslationY"
        android:duration="2000"
        android:valueFrom="0"
        android:valueTo="300"
        android:repeatCount="1"
        android:repeatMode="reverse"
        android:valueType="floatType"/>
    <objectAnimator
        android:propertyName="Alpha"
        android:duration="2000"
        android:valueFrom="1"        
        android:valueTo="0"        
        android:repeatCount="1"
        android:repeatMode="reverse"
        android:valueType="floatType"/>        
</set>


The animation is started programmatically with the following code.

...
ImageView iView = (ImageView) findViewById(R.id.ImageView1);
iView.setImageResource(R.drawable.green_rect);
AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(this, R.animator.animation1);
set.setTarget(iView);
set.start();
...

In Eclipse, the animation must be designed by hand. In Windows, Blend makes it much easier to design the animation interactively and test it.

For more info about animations, see Animating your UI.

Note For info about animations for Windows Store apps using JavaScript and HTML, see Animating your UI (HTML).

Top

Next steps

You can now create more robust Windows Store apps based on the apps that you started in these brief walkthroughs. With this foundation to build upon, we invite you to explore the following additional resources:

Also, be sure to visit our Community resources to learn how to get help and get connected through developer forums, blogs, developer camps and workshops, and local Microsoft events and contacts.

We think that Windows 8 will open up new app-building opportunities for you. We look forward to seeing all of the great apps that you're going to build!

Top

Reprinted with permission.



Comments

  • There are no comments yet. Be the first to comment!

Leave a Comment
  • Your email address will not be published. All fields are required.

Featured Videos

Best Practices for Windows Phone Proximity API

Visual Studio 2013 Tips and Tricks for Your Windows Apps (Video)

Arcade Programming Tutorial using GameMaker:Studio

Video: Introduction to XAML

Windows 8 App Spotlight

Recommended Partner Resources
 
Follow us: