Java programming technic question

Posts 13 of 3 · Page 1 of 1
Java programming technic question
I was ready some Android codes, then I saw this:
findViewById(R.id.myButton).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Do stuff
}
});
I just don't understand how you can have onClick(View v) inside
public void onClick(View v) {
// Do stuff
}
because to me findViewById(R.id.myButton).setOnClickListener(new View.OnClickListener() {

}); is a method, how can one have one method inside an other ?
I am aware that one can call a method inside another, this is not the case, or I am wrong.
So i am confused by this.
The code you posted can be rewritten as such

OnClickerListener newListener = new View.OnClickListener() {
public void onClick(View v) {
// Do stuff
}
}

findViewById(R.id.myButton).setOnClickListener(new Listener);

From my understanding, (and this is where yours and my definition of a method might differ), this is not a method inside another method.

What is happening is a new OnClickerListener object is being instantiated, containing a method called onClick. However, this object is also being set as the OnClickListener for findViewById(R.id.myButton) View object as well.

Hope this helps.
It�s a method declared on an inner class which is a way of faking a closure in java
Posts 13 of 3 · Page 1 of 1

Post a Reply

Similar Threads

Tags for this Thread

None

Need help?