One alternative pattern is to make the container class itself a listener.
public class MyClass implements View.OnClickListener {
@Override
public void onClick(View v) {
// Do something when button is clicked
}
public void initOrSomething() {
button.setOnClickListener(this);
}
}
However you may run into trouble if you have more than one button that needs to behave differently.
Another way is to have different listener classes for each button
public class Button1Listener implements View.OnClickListener {
@Override
public void onClick(View v) {
// Do something when button1 is clicked
}
}
public class Button2Listener implements View.OnClickListener {
@Override
public void onClick(View v) {
// Do something when button2 is clicked
}
}
button1.setOnClickListener(new Button1Listener());
button2.setOnClickListener(new Button2Listener());
Anonymous inner classes are just a more compact representation of the second pattern.
EDIT: Variations of both patterns are possible, where contents of the View object are examined to determine which button was clicked or constructor arguments are passed to the listener class to change listener behavior etc.