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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With