Android Development – Adding Screens & Button Handlers

By | May 2, 2010

Adding screens to an Android application is pretty straightforward. Coming from a web-centric .NET shop however, it took me a bit before I realized exactly how it was done. In this post I’ll be showing a bare bones way of adding screens to an Android app, along with some bare bones button navigation between the screens.

As usual, I’m assuming that you have your environment set up for Android development in Eclipse. Create a new Android project to start.

Activities

Screens in Android are defined (most of the time) in layout files. They are a part of an activity, one of the core components of an Android application. In addition to a layout, an activity also contains code that defines its behavior. You can see what activities your application contains by double clicking on the AndroidManifest.xml file and reviewing the Application Nodes section on the Application tab.

activitiesInManifest

From a bare bones perspective, to add a screen we must add an activity. Each activity must have a matching class file however, so we’ll add those first. Right click on the src node and click New –> Class.

newClass

Name this first new class screen1, and set the superclass to android.app.Activity. Ignore the warnings, we’re not going for style right now.

newActivityClass

Clicking on finish produces some truly bare bones code which we will flesh out below.

package com.screenssample;

import android.app.Activity;

public class screen1 extends Activity {

}

Now we need to add the actual activity that will use this new code. Returning to the Application tab of the Android manifest file, we click on Add in the Application Nodes section.

addActivity

We make sure to add the new element at the top level, in Application, and select Activity.

addActivity2

Then we name our activity the same as the backing class file we created above, screen1.

namedActivity

And that’s our first activity. Go ahead add a second activity named screen2 following the steps above, along with its backing code file.

Layouts

Before we can do anything else in any activity’s class, we need to define the associated layout for our new screen. Our layouts are contained in the res –> layout node in the Package Explorer.

layoutLocation

Right now we have one layout file, main.xml. This layout is loaded on application start up, as we can see by the code in main.java.

package com.screenssample;

import android.app.Activity;
import android.os.Bundle;

public class main extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}

The important line is the call to setContentView. We are passing R.layout.main to that method, which maps onto the layout defined in main.xml.

Adding Layouts

We will need to add two new layouts, one for each activity we added above. Each will have a button for navigation, and we will go from main to screen1 to screen2, back to main. So first we right click on the layout node pictured above and select New –> Android XML File.

newAndroidXmlFile

Enter the name of the new layout file (it has to be a valid filename) and make sure you don’t use uppercase characters. Yes, that’s right – I camel-cased the name of the layout file first and lost five minutes of my life to the fact that Android doesn’t want uppercase characters in layout files. After adding our new layout files, our layout folder looks like below.

screensAdded

Now we need navigation buttons on each of our screens. Double-click screen1, bringing up the basic screen designer in Eclipse.

basicScreenDesigner

There are a few ways you can add a button to this layout. We’re sticking with the mouse-driven way for now. Click and drag a TextView selection from the Views pane onto the layout surface, and then do the same with a Button selection.

buttonAdded

I detest default UI element ids (at least for buttons), so let’s change our button’s id to something more representative of what it’s doing, say nextScreen. We’ll change the button text as well. We will also change the text in the TextView to indicate what screen we’re on. As usual, there is more than one way to do this. We are going to use the Properties pane below the layout surface. Find the Id property, and change it to read @+id/nextScreen1. Then find the Text property and change it to Next screen.

idPropertyChanged

textPropertyChanged

Do the same for the main and screen2 screens, setting their id properties to nextScreenMain and nextScreen2 respectively. That finishes up our layout – now we have to tell our app to do something when the buttons are clicked.

Adding Button Handlers

Android provides a rich event-based system for controlling application UIs. We will be handling the button click events on each of our screens, bringing up the next activity in the chain when we click. Open up the main.java file, and below the setContentView method call start typing the below.

needAnImport

This was a pretty neat feature when I saw it pop up in the IDE. I’m used to Visual Studio, and the Intellisense there doesn’t seem quite as polished as what I’ve seen so far in Eclipse. Visual Studio 2010 does seem to equalize things some however. Either way, we see here that we need to import an additional package, namely android.widget. Do so, and enter the code below.

public class main extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        Button mainNext = (Button) findViewById(R.id.nextScreenMain);
        mainNext.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent i = new Intent();
                i.setClassName("com.screenssample", "com.screenssample.screen1");
                startActivity(i);
            }
        });

    }
}

The fun starts on line 8, where we are creating a reference to our button on the main screen. After that, on line 9 we are creating an anonymous method that will handle button clicks. Inside of our event handler we are spinning up our “screen1” activity by creating an Intent object with the proper class name. You can run the app at this point to test it out.

After that, finish out the example by adding similar code to the other two screens’ onCreate method, as shown below.

public class screen1 extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen1);

        Button mainNext = (Button) findViewById(R.id.nextScreen1);
        mainNext.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent i = new Intent();
                i.setClassName("com.screenssample", "com.screenssample.screen2");
                startActivity(i);
            }
        });

    }
}

public class screen2 extends Activity {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.screen2);

        Button mainNext = (Button) findViewById(R.id.nextScreen2);
        mainNext.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                Intent i = new Intent();
                i.setClassName("com.screenssample", "com.screenssample.main");
                startActivity(i);
            }
        });

    }
}

And there you have it – a basic Android application with three screens and (very) bare bones navigation. In future posts I’ll present more of a best practices approach on how to handle different screens (activities) within an Android application, as well as ways to optimize such.