While learning about Event Handling I came across the the below code
Button button = (Button) findViewById(R.id.button_send);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do something in response to button click
}
});
I'm not understanding why an instance of anonymous class that is implementing the onClick() button is passes as an argument?
Please explain me the procedure followed above with an example
I don't think there is a technical reason for doing this. I bet the author just wanted to illustrate a point while avoiding getting bogged down with the details, e.g. not having to create another class that extends View.OnclickListener.
Degreat Yartey
the greatest
In java you cannot pass functions as parameters to other functions. But objects.
Had it been java accepts functions as arguments it would have been like this:
button.setOnClickListener(playMusic); // where playMusic is a functionBut in java's architecture, that's not accepted in this present day, so you pass in an object instead, which is an OnClickListener object.
So the code you wrote above is the same as;
View.OnClickListener playMusic = new View.OnClickListener() { @Override public void onClick(View view) { media.startPlaying(); } } // and then pass playMusic to button onclick button.setOnClickListener(playMusic); // where playMusic is now an object