Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating an instance of an interface itself in Android

Tags:

android

Here is code

btn.setOnClickListener(new View.OnClickListener() {
  public void onClick(View v) {
    //...
  }
});

where setOnClickListener looks like:

public void setOnClickListener(android.view.View.OnClickListener l) { /* compiled code */ }

However, what's new View.OnClickListener() itself? It turns out this is an interface:

//View.class
public static interface OnClickListener {
    void onClick(android.view.View view);
  }

That is, here btn.setOnClickListener(new View.OnClickListener() .... I create an instance of the interface. No, this is not the instance of a class which implements this interface.

How is it possible to create an instance of an interface?

like image 590
Alan Coromano Avatar asked Oct 03 '22 14:10

Alan Coromano


1 Answers

Yes, it is. It is a Anonymous class that implements the interface. The onclick that goes after is the implementation of onclick.

Try to do it like this:

View.OnClickListener listener=new View.OnClickListener() {
  public void onClick(View v) {
    //...
  }
};
btn.setOnClickListener(listener);

This may look more clear.

like image 138
wtsang02 Avatar answered Oct 07 '22 20:10

wtsang02