0

This is the code that does something in response to a View object being clicked (e.g. a button being clicked):

final OnClickListener exampleListener = new OnClickListener()
{
public void onClick(View arg0) {
//Code here that does something upon click event.
}
};

Button exampleButton = (Button)this.findViewById(R.id.firstButton);

exampleButton.setOnClickListener(exampleListener);

I don't understand the code. Is this code creating an overridden method called onClick which belongs to the parent OnClickListener class on the fly?

Is the following code equivalent to the above code?:

final OnClickListener exampleListener = OnClickListener.onClick()
{  

  public void onClick(View arg0) {
  //Code here that does something upon click event.};
}

2 Answers2

2

What the first code actually does is declare and instantiate a class that implements OnClickListener. This is called an Anonymous Class.

The second code is not the same and won't work, I'd suggest you to forget it as fast as possible.

FD_
  • 12,947
  • 4
  • 35
  • 62
1

You should read about Anonymous classes.

OnClickListener is an interface. In the code, you are defining a class and creating a new object at the same time.

For your second question, the answer is no. They are not equivalent as 'OnClickListener' is an interface and you can't define a single method within an interface(even if the interface has only one method).

To be more clear, this doesn't have anything to do with Eclipse.

If you're more interested, what you are doing is creating a call back object and registering it as a listener

Community
  • 1
  • 1
Sundeep
  • 1,536
  • 5
  • 23
  • 35