I saw this code when looking at an Android example:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EditText editNumber;
Button btnCall = (Button) this.findViewById( R.id.btnCall);
editNumber = (EditText) this.findViewById(R.id.editNumber);
btnCall.setOnClickListener(
new OnClickListener() {
public void onClick(View v) {
call();
}
});
// ...
}
Here:
new OnClickListener() {
public void onClick(View v) {
call();
}
}
is passed to setOnClickListener() as a parameter. What I don’t understand is what code inside {...} does here? if new OnClickListener() calls the constructor, and the constructor returns an object, yes, object can be passed to method as a parameter, but what is:
{
public void onClick(View v) {
call();
}
}
doing here? It looks like a method definition?
Thanks a lot for the help!
As @Perception said, it is an anonymous inner class.
btnCall.setOnClickListenter()is expecting an argument that has the typeOnClickListener. You could instantiate a concrete reference to anOnClickListenerand pass that as an argument but if you are never going to refer to it again, sometimes it is easier to simply make an anonymous inner class.