Chapter 4

Listeners

Like many GUI systems, Android is event based. User interaction may trigger an event and you can write code that gets executed when the event occurs. The class that contains code to respond to a certain event is called a listener. In this chapter you learn how to handle events and write listeners.

Overview

Most Android programs are interactive. The user can interact with the application easily thanks to the event-driven programming paradigm the Android framework offers. To make the program do something in response to a certain event, you need to write a listener for that event.

There are two ways to register a listener in Android. The first is by using a callback method in the layout file. This is very straightforward but only works for the onClick event. The second method is by writing a listener class and register it with a view class in your program.

Note

A listener runs on the main thread. This means you should use a different thread if your listener takes a long time (say, more than 200ms) to run. Or else, your application will look unresponsive during the execution of the listener code. You have two choices for solving this. You can either use a handler or an AsyncTask. The handler is covered in Chapter 7, “Handling the Handler” and AsyncTask in Chapter 9, “Asynchronous Tasks.” For long-running tasks, you should also consider using the Java Concurrency Utilities.

Example

As an example of the first method, consider the MulticolorClock project that accompanies this book. It is a simple application with a single activity that shows an analog clock that can be clicked to change its color. AnalogClock is one of the widgets available on Android, so writing the view for the application is a breeze. The main objective of this project is to demonstrate how to write a listener by using a callback method in the layout file.

The manifest for MulticolorClock is given in Listing 4.1. There is nothing out of ordinary here and you should not find it difficult to understand.

Listing 4.1: The manifest for MulticolorClock

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.example.multicolorclock"

    android:versionCode="1"

    android:versionName="1.0" >

 

    <uses-sdk

        android:minSdkVersion="8"

        android:targetSdkVersion="17" />

 

    <application

        android:allowBackup="true"

        android:icon="@drawable/ic_launcher"

        android:label="@string/app_name"

        android:theme="@style/AppTheme" >

        <activity

            android:name="com.example.multicolorclock.MainActivity"

            android:label="@string/app_name" >

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

    </application>

</manifest>

Now comes the crucial part, the layout file. It is called activity_main.xml and located under the res/layout directory. The layout file is presented in Listing 4.2.

Listing 4.2: The layout file in MulticolorClock

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context=".MainActivity">

 

    <AnalogClock

        android:id="@+id/analogClock1"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_alignParentTop="true"

        android:layout_centerHorizontal="true"

        android:layout_marginTop="90dp"

        android:onClick="changeColor"/>

 

</RelativeLayout>

The layout file defines a RelativeLayout containing an AnalogClock. The important part is the onClick attribute in the AnalogClock declaration.

android:onClick="changeColor"

This means upon the user’s clicking the AnalogClock widget, the changeColor method in the activity class will be called. For a callback method like changeColor to work, it must have no return value and accept a View argument. The system will call this method and pass the widget that was clicked.

The changeColor method is part of the MainActivity class shown in Listing 4.3.

Listing 4.3: The MainActivity class in MulticolorClock

package com.example.multicolorclock;

 

import android.app.Activity;

import android.graphics.Color;

import android.os.Bundle;

import android.view.Menu;

import android.view.View;

import android.widget.AnalogClock;

 

public class MainActivity extends Activity {

 

    int counter = 0;

    int[] colors = { Color.BLACK, Color.BLUE, Color.CYAN,

            Color.DKGRAY, Color.GRAY, Color.GREEN, Color.LTGRAY,

            Color.MAGENTA, Color.RED, Color.WHITE, Color.YELLOW };

 

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

    }

 

    @Override

    public boolean onCreateOptionsMenu(Menu menu) {

        // Inflate the menu; this adds items to the action bar if it

        // is present.

        getMenuInflater().inflate(R.menu.main, menu);

        return true;

    }

 

    public void changeColor(View view) {

        if (counter == colors.length) {

            counter = 0;

        }

        view.setBackgroundColor(colors[counter++]);

    }

}

Pay special attention to the changeColor method in the MainActivity class. When the user clicks (or touches) the analog clock, this method will be called and receive the clock object. To change the clock’s color you call its setBackgroundColor method, passing a color object. On Android, colors are represented by the android.graphics.Color class. The class has pre-defined colors that make creating color objects easy. These pre-defined colors include Color.BLACK, Color.Magenta, Color.GREEN, and others. The MainActivity class defines an array of ints that contains some of the pre-defined colors in android.graphics.Color.

 

    int[] colors = { Color.BLACK, Color.BLUE, Color.CYAN,

            Color.DKGRAY, Color.GRAY, Color.GREEN, Color.LTGRAY,

            Color.MAGENTA, Color.RED, Color.WHITE, Color.YELLOW };

There is also a counter that points to the current index position of colors. The changeColor method inquiries the value of counter and changes it to zero if the value is equal to the array length. It then passes the pointed color to the setBackgroundColor method of the AnalogClock.

        view.setBackgroundColor(colors[counter++]);

The application is shown in Figure 4.1.

 4_1

Figure 4.1: The MulticolorClock application

Touch the clock to change its color!

Summary

In this chapter you learned the basics of Android event handling and how to write listeners.

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

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