That's quite simple: What you are doing is just creating a class. For the JVM (or dalvik in this case), it doesn't matter if the class is it's own compilation unit (a file), an inner class or an anonymous class(*). So you have three equally valid options:
Option 1 Your example:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
});
Option 2 named inner class:
public MyActivity extends Activity {
static class MyListener implements View.OnClickListener {
@Override
public void onClick(View v) {
// do something
}
}
....
button.setOnClickListener(new MyListener());
}
and Option 3 Different Files:
File MyListener.java
public class MyListener implements View.OnClickListener {
@Override
public void onClick(View v) {
// do something
}
}
File MyActivity.java
import MyListener.java
public MyActivity extends Activity {
....
button.setOnClickListener(new MyListener());
}
Which of these options you use is completely subjective - Depending on your needs and usage, one or the other makes more sense.
However, generally in UI listeners, you don't want to have any logic that is disjunct from the logic of the Activity you are programming. Hence you use the anonymous class, because all the code stays in one place and makes it decently readable.