A computer is a machine that follows a list of instructions called a program. An Android device is a computer and an app is a program.

Inside the device are containers called variables that hold values such as numbers or pieces of text. The value in a variable can easily be changed; that’s why it’s called a “variable”.

A big variable that can contain smaller variables is called an object. The smaller variables are called the fields or members of the object and are often objects in their own right. That means we can store a little object inside a bigger one. An object can also have lists of instructions attached to it — in effect, little programs — called methods. The methods of an object cannot be changed. They are permanently attached to the object.

There are many classes of objects. For example, an object of class ImageView displays an image, and an object of class Button can respond when touched. All of the objects of a given class have exactly the same set of methods attached to them. For example, every object of class Button has a method named setEnabled(boolean), which makes the Button eligible or ineligible for touching.

But we often need two or more Buttons that take different actions, such as “purchase” vs. “cancel”. We cannot accomplish this by attaching a different method to each Button. All the Buttons belong to the same class and therefore must have identical methods. Similarly, a Button that changes from “play” to “pause” would have to do this without changing its methods.

The solution is to create a separate object called an OnClickListener. Attached to the listener is a method named onClick(View), containing the instructions to be executed when a Button is touched. (“Click” was the word for “touch” in early versions of Android.) The listener is stored in a field of the Button and lies dormant there until the touch occurs. When that happens, the onClick method attached to the listener is automatically executed.

It would be hard to make many classes of Buttons, each with a different set of methods. But an OnClickListener is a much simpler type of object. It is practical to create a listener with an onClick method containing instructions to “purchase”, and another listener whose onClick performs a “cancel”. Each listener can then be stored into a different Button, yielding different behavior when each Button is touched. And since the contents of a field can be changed, the “play” listener in a Button could be replaced with a “pause” listener.

As a footnote, there’s a different way of setting up a method to be executed when a Button is touched. If the Button is created with a <Button> element in an XML layout file, the method can be designated with the android:onClick attribute of the element. This is a convenient alternative for a Button whose behavior does not change.