0
add.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        counter +=19;
        display.setText("your total is "+ counter);
    }
});

i was learning android programming but what this code means here add is Button object , and we are using method setOnClickListener and basically what is passed as a argument to it , which is confusing. counter is int variable and display is TextView object used for producing text when button is pressed. please reply

isaias-b
  • 2,255
  • 2
  • 25
  • 38
  • I think your question is not focussing on android explicitly. If you are really referring to the argument passed into the method and what the argument exactly means. Then you are asking a more general question like [this](http://stackoverflow.com/q/355167/3165552) or [this](http://stackoverflow.com/q/10778578/3165552). Since this post had only 5 views for now, you can think about adding more tags to your post to attract a broader user group to read the question. – isaias-b Jun 17 '14 at 12:35

1 Answers1

1

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

isaias-b
  • 2,255
  • 2
  • 25
  • 38