Android programming: a simple activity

To get started programming an Android application, I’m assuming you have the Eclipse IDE with Android Developer Tools (ADT) installed. You can get this package here. To test your apps, you’ll need to set up one or more Android emulators, which you can do using the Android Virtual Device Manager from within Eclipse (there should be an icon on the default toolbar, or you can get it from the Window menu).

You may find that the emulator takes ages (well, several minutes) to start up. If so, and if you have the right kind of Intel processor, you should consider installing the Intel Hardware Acceleration Execution Manager (HAXM). Once installed (assuming your system supports it), select the Intel Atom option for the CPU/ABI in the Android Virtual Device Manager when setting up your emulator. This cuts the startup time down to a few seconds.

Assuming you’ve got everything installed, let’s create an Android app. In Eclipse, click the ‘New’ icon and select Android–>Android Application Project, then Next. Enter the app, project and package names in the next dialog, then click ‘Next’ again. In the Configure Project dialog, we’ll start with the most basic app, so uncheck the ‘Create custom launcher icon’ and ‘Create activity’ boxes, then click Finish. Eclipse will now create a skeleton project.

For example, suppose we want to create a simply app that displays a button that toggles its text between ‘Off’ and ‘On’ when you click it. We’ll call the package growe.ex01onoff.

Activities

You won’t be able to run this project, since there’s no Java source code yet, so the first thing we need to do is add some. An Android app is built using one or more Activity objects, so we’ll add an Activity to our project. To do this, right click on the package in the Package Explorer and select ‘New…’, then pick Android–>Android Activity and Next. Then select ‘Blank activity’ and Next. In the Blank Activity dialog, give the activity a name such as OnOffActivity and accept the generated layout name and title. Click the Launcher Activity box since we want this activity to be launched when the app starts.

You can click Finish here, since clicking Next just gives you a Preview dialog where you can see the pending changes to the various files in your project that adding this activity will make.

You should now find that Eclipse has created a Java file called OnOffActivity.java, with the following code:

package growe.ex01onoff;

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

public class OnOffActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_on_off);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.on_off, menu);
		return true;
	}

}

The onCreateOptionsMenu() method (not surprisingly) creates a menu, but we don’t want one in this simple app so you can safely comment out this code for now.

The onCreate() method is called when this Activity starts, but since an app can have several Activities, how does it know that we want this one to be the startup Activity? The answer is in the AndroidManifest.xml file, which contains the lines:

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="growe.ex01onoff.OnOffActivity"
            android:label="@string/title_activity_on_off" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

Within the activity tag, we see the name of the OnOffActivity and an intent-filter. The action of  android.intent.action.MAIN indicates that it is the entry point of the app. (We’ll worry about intents later.)

Resources

Going back to the Java code, the call to setContentView() draws the user interface. The argument of this call illustrates the way apps refer to resources that are defined elsewhere, usually in XML files. Every Android app creates a Java class called R. The source code for R can be found in the gen folder and, since it’s generated by Eclipse, it shouldn’t be edited since any changes will just be overwritten. Within the R class are defined other classes that contain int codes referring to the resources that are defined in the various XML files within the res folder. Within R, you’ll find a class called layout which contains an int named activity_on_off. If you look within the res folder, you’ll find a layout folder which contains the file activity_on_off.xml. This file contains the definitions of the user interface elements that are to be drawn on the screen when this layout is used. The file generated by Eclipse when an activity is created contains a single TextView which displays the text ‘Hello world!’.

We want the interface to display a button instead. We could do this by editing the XML file directly, but Eclipse has a graphical editor which allows interfaces to built visually. To do this, open the activity_on_off.xml file and click on the Graphical Layout tab at the bottom. Click on the TextView and delete it, then select a button from the Form Widgets menu on the left and drag it onto the window. You’ll notice that a Properties box on the right displays all the properties of this button that can be set. We want the button to start off displaying the caption ‘Off’. One way of doing this is just to write Off in the Text property, but there is a more general way of doing this using a String resource. 

Why should we bother with this more general way of defining strings? A major reason is that it makes apps easier to internationalize by writing strings in different languages. We can write a set of string resources for each language we want to support and then just load in the correct set of strings when we change languages. This works only if each string is given a resource name rather than hard coded.

To add a new String resource, open the res–>values–>strings.xml file. If you look at the XML code first, you’ll see several strings already defined. To add a new String, go to the Resources tab at the bottom, click the Add… button and then double-click String in the dialog. Give the resource a name like offText and a value of Off. While you’re at it, add another String resource called onText with a value of On, which we’ll use later. Make sure to save strings.xml before proceeding.

Now go back to activity_on_off.xml and select the button again. In the properties box click the … button for the Text property and you should see a list of all the string resources defined in strings.xml. Select offText, and the button’s caption should now be Off.

At this point you can run the app in your emulator and you should see the white screen with the Off button on it. Pressing the button has no effect, of course, because we haven’t added an event handler to the button yet.

Event handlers

Unlike many other IDEs, it seems that Eclipse doesn’t provide any shortcuts to adding event handlers to components, so the only option is just to write in the code by hand.

There are two ways of attaching an event handler to a button. The easiest is to find the On Click property of the button (listed in the View section in the properties box) and provide the name of a method that will handle the click event. This method must be placed in the Activity class that contains the button in its layout. If we specify the event handler as toggleOnOff, then we can modify the OnOffActivity class as follows:

package growe.ex01onoff;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.app.Activity;

public class OnOffActivity extends Activity {
	boolean on = false;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_on_off);
	}

	public void toggleOnOff(View view) {
		Button onOffButton = (Button) view;
		onOffButton.setText(on ? R.string.offText : R.string.onText);
		on = !on;
	}
}

The event handler must always have the signature shown. It must be public, void, and have a single argument of class View (which is the View that triggered the event; in this case, the button). Here, we’ve defined a boolean variable on which stores the state of the button and we set the text of the button according to the state of this variable, then toggle the variable.

The second way of attaching an event handler to a button is done entirely within the Activity class’s onCreate() method:

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_on_off);

		Button onOffButton = (Button) findViewById(R.id.onOffButton);
		onOffButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View view) {
				Button button = (Button) view;
				button.setText(on ? R.string.offText : R.string.onText);
				on = !on;
			}
		});
	}

First, we need to find the button, which we do using the findViewById() method on line 6. Each UI component is assigned an ID number in the R class, and this method retrieves a reference to the component using this ID. Next, we attach an OnClickListener to the button using setOnClickListener(). Within this listener, we override the onClick() method, which becomes the event handler, so it contains the same code as we had earlier.

Advertisements
Post a comment or leave a trackback: Trackback URL.

Trackbacks

  • By Android: explicit intents | Programming tutorials on February 19, 2014 at 6:18 PM

    […] a new project in Eclipse as described in our previous post. Add a main Activity called StartActivity which is displayed when the app starts. The layout of […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: