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 android package:

a pre-activity time the package com.commonsware.android.skeleton;

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

It's worth noting that not every Java SE class is available to Android programs. Visit the Android class reference2 to see what is and is not available.

Activities are public classes, inheriting from the android.app.Activity base class. In this case, the activity holds a button (btn):

public class Now extends Activity implements View.OnClickListener { Button btn;

■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 OnClickListener.

@Override public void onCreate(Bundle icicle) { super.onCreate(icicle);

btn = new Button(this); btn.setOnClickListener(this); updateTime(); setContentView(btn);

The onCreate() 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 (new Button(this)), tell it to send all button clicks to the activity instance itself (via setOnClickListener()), call a private updateTime() method (discussed in a moment), and then set the activity's content view to be the button itself (via setContentView()).

■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.

2. http://code.google.com/android/reference/packages.html

I discuss that magical Bundle icicle in Chapter 16. For the moment, consider it an opaque handle that all activities receive upon creation.

public void onClick(View view) { updateTime();

In Swing, a JButton click raises an ActionEvent, which is passed to the ActionListener configured for the button. In Android, a button click causes onClick() to be invoked in the OnClickListener 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 updateTime() method:

private void updateTime() { btn.setText(new Date().toString());

When we open the activity (onCreate()) or when the button is clicked (onClick()), we update the button's label to be the current time via setText( ), which functions much the same in Android as JButton does in Swing.

0 0

Post a comment