Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

364 HOUR 24:Writing Android Apps


The first argument to Log.i()identifies the app and the second contains
the message.
When you designed the app’s user interface earlier, you set the On Click
property of each button to processClicks. This indicated that a method
called processClicks()would be called when a user clicked a widget on
the screen. Now it’s time to implement that method. Addthese statements
to LeaderActivitybelow the onCreate()method:
public voidprocessClicks(View display) {
Intent action;
int id = display.getId();
}

This method is called with one argument, a Viewobject from the
android.viewpackage. AViewis a visual display of some kind in an app.
In this case, it’s the screen containing the Dialer, Browser, and Maps but-
tons.
The Viewobject’s getId()method returns the ID of the button that was
clicked: phonebutton, webbutton, or mapbutton.
This ID is stored in the idvariable so it can be used in a switchstatement
to take action based on the click:
switch(id) {
case(R.id.phonebutton):
// ...
break;
case(R.id.webbutton):
// ...
break;
case(R.id.mapbutton):
// ...
break;
default:
break;
}

This code will take one of three actions, using the integer of each ID as the
conditional in the switch. The first statement in the processClicks()
method creates a variable to hold an Intentobject, a class in Android’s
android.contentpackage:
Intent action;

Intents in Android are howActivities tell another Activity what to do.
They’re also the way an app communicates with the Android device.
Free download pdf