-1

While learning about Event Handling in android I came across the below code

Here are few questions that I have

1) Why an instance of an anonymous class that is implementing the View.OnClickListener() interface is passed as an argument to setOnClickListener()?

2) What is the benefit of passing this instance as an argument?

 Button button    =    (Button) findViewById(R.id.button_send);
 button.setOnClickListener(new View.OnClickListener() // explain this {
 public void onClick(View v) {
    // Do something in response to button click
}});
black sheep 369
  • 564
  • 8
  • 19

2 Answers2

1

The Goal: You want to do something when the user clicks on the button.

What you need: You need to know when the user clicks on the button.

How do you know: Using this View.OnClickListener interface.

This is the source code of the View.OnClickListener:

    /**
     * Interface definition for a callback to be invoked when a view is clicked.
     */
    public interface OnClickListener {
        /**
         * Called when a view has been clicked.
         *
         * @param v The view that was clicked.
         */
        void onClick(View v);
    }

This is something like you pass a method A to another method B, and the method B invokes the method A when certain event happen.

In this View.OnClickListener case, the method you pass is invoked when the user clicks on the button.

Technically, you implement the View.OnClickListener and create an instance of it on the fly and pass it to the method setOnClickListener().

The onClick(View v) method will get invoked when the user taps on the button. So the code inside the onClick(View v) method will get executed whenever the user taps on the button.

Bob
  • 13,447
  • 7
  • 35
  • 45
0

You aren't passing an interface (View.OnClickListener) but rather an instance of an implementation of that interface.

The instance is typically anonymous because creating a named (possibly final) instance of it is essentially useless; the only place it is likely ever to be used is as an argument to a single setter. And any implementation of the interface you create in order to make a named instance will probably encapsulate component-specific behaviour that make little sense to expose as a named class.

This is explained very well in this SO answer.