ptg7068951
Designing a Real App 363
LISTING 24.1 The Starting Text of LeaderActivity.java
1: packageorg.cadenhead.android;
2:
3: importandroid.app.Activity;
4: importandroid.os.Bundle;
5:
6: public classLeaderActivity extendsActivity {
7: /* Called when the activity is first created. /
8: @Override
9: public voidonCreate(Bundle savedInstanceState) {
10: super.onCreate(savedInstanceState);
11: setContentView(R.layout.main);
12: }
13: }
Like all Activities, theLeaderActivityclass is a subclass of Activityin
the android.apppackage, which contains the behavior necessary to dis-
play a screen, collect user input, save user preferences, and so on.
The onCreate()method defined in lines 9–12 is called when the class is
loaded. The first thing the method does is use super()to call the same
method in its superclass. Next, it calls setContentView(), a method that
selects the screen that will be displayed. The argument to this method is an
instance variable, R.layout.main, that refers to the file main.xmlin
/res/layout. As you may recall, the ID of a resource is its filename with-
out the extension.
The first thing you must do in the LeaderActivityclass is give it a class
variable. Add the following statement right below the class definition:
public static finalString TAG = “Leader”;
This variable serves as an identifier for the class, which you use to log
events that occur as it runs. Android classes can log their activities to let
you know what’s happening in the app. Here’s one of the log statements
you will add later:
Log.i(TAG, “Making call”);
This statement displays a log message tagged with the name “Leader.”
The Logclass in the android.utilpackage displays messages in the log.
This class has five different methods to log messages, each of which indi-
cates what type of message it is, such as a warning, debugging message, or
error. The i()method is for info messages—information that explains
what’s going on in the app.
NOTE
Yo u c a n o p e n t h e R.javafile
for editing in the /res/gen/
org.cadenhead.androidfolder
to learn more about why the
mainresource is referred to as
R.layout.main. The Rclass is
generated automatically by the
Android SDK to enable
resources to be referenced by
their IDs. You never should edit
this class yourself.