The argument is a new anonymous object of an anonymous type subclassing from View.OnClickListener
being added to your button called add
. The definition refers to the argument given by this code new View.OnClickListener() { /*...*/ }
.
That is what happens in your line. Whenever the button add
is pressed the method onClick
will be called on the anonymous object being passed in. The code inside the overriden onClick
method then gets executed.
You can make it clearer by separating the anonymous class into a named class like the following:
class MyButtonListener implements View.OnClickListener {
private int counter;
private TextView display;
public MyButtonListener(int counter, TextView display) {
this.counter = counter;
this.display = display;
}
@Override
public void onClick(View v) {
counter +=19;
display.setText("your total is "+ counter);
}
}
And still use an anonymously created object, since it is not bound to a named variable and pass it again directly to your add
button. But now you use a named class called MyButtonListener
add.setOnClickListener(new MyButtonListener(counter, display));
Notice that now you must pass everthing needed into the object. Like the counter
and display
variables.
Hope this helps
The listener thing is basically a pattern called observer which can be used to decouple multiple handlers to a button from the button itself. This way they both doesnt know directly about each other, which allow both to evolve independently by the use of inheritance.
Anonymous classes are a way to quickly create subclasses. For more information about anonymous classes take a look at this site