The Activity
Your project’s src/ directory contains the standard Java‑style tree of directories based upon the Java package you used when you created the project (i.e., resulted in ). Inside the innermost directory you should find a pregenerated source file named , which is where your first activity will go. This activity will contain a single button that displays the time the button was last pushed (or the time the application was started if the button hasn’t been pushed).
Open in your editor and paste in the following code:
Or, if you download the source files off the CommonsWare Web site, you can just use the project directly.
Let’s examine this piece‑by‑piece.
Dissecting the Activity
The package declaration needs to be the same as the one you used when creating the project. And, like in any other Java project, you need to import any classes you reference. Most of the Android‑specific classes are in the package:
It’s worth noting that not every Java SE class is available to Android programs. Visit the Android class reference[3]to see what is and is not available.
Activities are public classes, inheriting from the base class. In this case, the activity holds a button ():
Note
A button, as you can see from the package name, is an Android widget, and widgets are the UI elements that you use in your application.
Since, for simplicity, we want to trap all button clicks just within the activity itself, we also have the activity class implement .
The method is invoked when the activity is started. The first thing you should do is chain upward to the superclass, so the stock Android activity initialization can be done.
In our implementation, we then create the button instance (), tell it to send all button clicks to the activity instance itself (via ), call a private method (discussed in a moment), and then set the activity’s content view to be the button itself (via ).
Note
All widgets extend the View base class. We usually build the UI out of a hierarchy of views, but in this example we are using a single view.
I discuss that magical in Chapter 16. For the moment, consider it an opaque handle that all activities receive upon creation.
In Swing, a click raises an , which is passed to the configured for the button. In Android, a button click causes to be invoked in the instance configured for the button. The listener is provided the view that triggered the click (in this case, the button). All we do here is call that private method:
When we open the activity () or when the button is clicked (), we update the button’s label to be the current time via setText(), which functions much the same in Android as does in Swing.
Дата добавления: 2015-05-16; просмотров: 778;