Creating Your First Activity

You may have already created your first activity if you created a project using the New Android Project Wizard in Chapter 3: the MainActivity activity. Open the MainActivity.java file in your project to enhance it in the following sections.

Starting with onCreate

The entry point into your application is the onCreate() method. The code for the MainActivity.java file already contains an implementation of the onCreate() method. It’s where you start writing code! For now, your code should look like this:

public class MainActivity extends Activity {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

}

}

You write the initialization code directly below the setContentView() method.

warning_bomb.eps Be sure to always include this method call to your onCreate() method:

super.onCreate(savedInstanceState);

It’s required for the application to run. This line directs the base Activity class to perform setup work for the MainActivity class. If you omit this line of code, you receive a runtime exception.

Telling Android to display the user interface

By default, an activity has no idea what its user interface is. It can be a simple form that allows the user to type information to be saved; a visual, camera-based, augmented, virtual reality application (such as Layar in the Google Play Store); or a drawn-on-the-fly user interface, such as in a 2D or 3D game. As a developer, it’s your job to tell the activity which layout the activity should load.

To show the user interface onscreen, you have to set the content view for the activity, by adding this line of code:

setContentView(R.layout.activity_main);

R.layout.activity_main is the activity_main.xml file that’s located in the res/layouts directory. It’s the layout you define in the Chapter 4.

Handling user input

The Silent Mode Toggle application has little user interaction. The only user interaction that your application will have is a single button that the user taps to toggle silent mode.

To respond to this tap event, you need to register an event listener, which responds to an event in the Android system. Though you find various types of events in the Android system, two of the most commonly used are keyboard events and touch events (also known as clicks).

Keyboard events

A keyboard event occurs whenever a particular keyboard key is pressed. For example, if the user presses the Alt+E hot key in your application, you may want the view to toggle into Edit mode. Responding to keyboard events allows you to do this. If you need to override the onKeyDown method to use your own keyboard event, do it this way:

@Override

public boolean onKeyDown(int keyCode, KeyEvent event) {

// TODO Auto-generated method stub

return super.onKeyDown(keyCode, event);

}

Touch events

A touch event occurs whenever the user taps a widget on the screen. The Android platform recognizes each tap event as a click event. Examples of views that can respond to touch events include (but aren’t limited to)

check.png Button

check.png ImageButton

check.png EditText

check.png Spinner

check.png ListView Rows

check.png MenuItem

tip.eps All views in the Android system can react to a tap; however, some widgets have their clickable property set to false by default. You can override this setting in your layout file or in code to allow a view to be clickable by setting the clickable attribute on the view or the setClickable() method in code.

Writing your first event handler

For your application to respond to the click event of the user toggling silent mode, you respond to the click event that’s exposed by the button.

Entering the code

Type into your editor the code shown in Listing 5-1. It demonstrates how to implement a click handler for toggleButton. The code consists of the entire onCreate() method with the new code. You can either fill in the button code (in bold) or overwrite your entire onCreate code.

Listing 5-1: The Initial Class File with a Default Button OnClickListener

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Button toggleButton = (Button)findViewById(R.id.toggleButton);

toggleButton.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {

}

});

}

This listing uses the findViewById() method, which is available to all activities in Android. This method, which allows you to find any view inside the activity’s layout and do some work with it, always returns a View class that you must cast to the appropriate type before you can begin. In the following code (which is a line from Listing 5-1), you’re casting the returned View from findViewById() to a Button (which is a subclass of View).

Button toggleButton = (Button)findViewById(R.id.toggleButton);

Immediately following this line of code, you start setting up the event handler.

The event handling code is placed inline after you retrieve the Button from the layout. Setting up the event handler is as simple as setting a new View.OnClickListener. This click listener contains an onClick() method that’s called after the user taps the button. It’s where you place the code to handle the silent mode toggle.

warning_bomb.eps Be sure to cast to the appropriate type. If the type in your layout file is different from what you’re casting it to (if you’re trying to cast an ImageView in the layout file to ImageButton, for example), you’ll crash your application.

When you type this code into your editor, you may see red, squiggly lines, as shown in Figure 5-2. These lines are Eclipse’s way of telling you that it doesn’t know what the “button” is.

Figure 5-2: Eclipse informs you that it cannot find the class.

9781118417454-fg0502.tif

Follow these steps to correct the problem:

1. Place the cursor over the squiggly line and leave it there for a moment.

A small context window opens to give you several options. (Refer to Figure 5-2.)

2. Select the first option — Import ‘Button’.

The following import statement is added to the top of the file:

import android.widget.Button;

This import statement informs Eclipse where the Button is located in the Android packages.

Extracting the code to a method

The code is starting to become unwieldy and difficult to read. At this point, the best thing you can do is extract the new button code to a method that you can call from within onCreate(). To do it, you create a private void method named setButtonClickListener() that contains the button code you just typed. This new method is placed in the onCreate() method. The new code is shown in Listing 5-2.

Listing 5-2: Button Listener Extracted to a Method

public class MainActivity extends Activity {

/** Called when the activity is first created. */

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

setButtonClickListener();8

}

private void setButtonClickListener() { 11

Button toggleButton = (Button)findViewById(R.id.toggleButton);

toggleButton.setOnClickListener(new View.OnClickListener() {

public void onClick(View v) {

// TODO Auto-generated method stub

}

});

}

}

Listing 5-2 works this way:

8 On this line, a method is called to set up the button click listener.

11 The new method is getting called.

Now you can respond to the click event by providing code for the onClick() method of your button.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset