Defining Activities

Recall that Android applications comprise a number of different activities. Every activity must be registered within the Android manifest file before it can be used. You need to update the manifest file each time you add a new activity to an application.

Each activity represents a specific task to be completed, often with its own screen. Activities are launched in different ways, using the Intent mechanism. Each activity can have its own label (name) and icon but uses the application's generic label and icon by default.

You can register each new activity in the Application Nodes section of the Application tab. Each new activity has its own <activity> tag in the resulting XML. For example, the following XML excerpt defines an activity class called DroidActivity:

<activity android:name=".DroidActivity" />

This activity must be defined as a class within the application package.

To register a new activity in the Droidl project, follow these steps:

1. Open the Droidl project in Eclipse.

2. Right-click /src/com.androidbook.droid1 and choose New Class. The New Java Class window opens.

3. Name your new class DroidActivity2.

4. Click the Browse button next to the Superclass field and set the superclass to android.app.Activity.

5. Click the Finish button. You see the new class in your project.

6. Make a copy of the main.xml layout file in the / res/layout resource directory for your new activity and name it second.xml. Modify the layout so that you know it's for the second activity. For example, you could change the text

Registering Activities

Try It Yourself

string shown. Save the new layout file.

7. Open the DroidActivity2 class. Right-click within the class and choose ▼ Source-Override/Implement Methods.

8. Check the box next to the onCreate(Bundle) method. This method is added to your class.

9. Within the onCreate() method, set the layout to load for the new activity by adding and calling the setContentView(R.layout.second) method. Save the class file.

10. Open the Android manifest file and click the Application tab of the resource editor.

11. In the Application Nodes section of the Application tab, click the Add button and choose the Activity element. The attributes for the activity are shown in the right side of the screen.

WOut!

If you have an existing Activity selected, you'll be adding to that. Instead, select None or choose the Create a New Element at the Top Level, in Application radio button at the top of the dialog.

12. Click the Browse button next to the activity Name field. Choose the new activity you created, DroidActivity2.

13. Save the manifest file. Switch to the AndroidManifest.xml tab to see what the new XML looks like.

You now have a new, fully registered DroidActivity2 activity that you can use in your application. ▲

0 0

Post a comment