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.

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.

Eclipse New Android Application Project menu command

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();


Eclipse integrated development environment

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.

Adding a new page in Visual Studio

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.

Open in Blend menu command

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.

More by Author

Must Read