Using anonymous classes when calling interfaces
I'm trying to fully integrate the concept of anonymous classes and interfaces in Android and Java. In another thread a reply was given to a question regarding something like:
getQuote = (Button) findViewById(R.id.quote);
getQuote.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// Do something clever
}
}
"What is sent in there is an anonymous class, you could just as well make a separate class which implements OnClickListener and make an instance of that class and send that in as the argument to setOnClickListener." -- Jon
My question is what would the code look like if you went the long route of creating a separate class that implements OnClickListener? I think if I开发者_如何学Python saw the long route it would make more sense. Many thanks!
class MyClass implements View.OnClickListener {
@Override
public void onClick(View v) {
// Do something clever
}
}
// Calling Code
MyClass listener = new MyClass();
getQuote.setOnClickListener(listener);
When you're creating a lot of them and as they're not required apart from where you declare and bind it then the anonymous class is considered a neater approach.
//somewhere in your class or even as its own top-level class:
static class MyOnClickListener implements View.OnClickListener {
@Override
public void onClick(View v) {
// Do something clever
}
}
getQuote.setOnClickListener(new MyOnClickListener());
Note that the location of the explicitly defined class can vary. If it's contained inside your class you might be able to declare it static
or you might not (depending on the clever stuff needs access to the instances members).
It would look like this:
getQuote = (Button) findViewById(R.id.quote);
getQuote.setOnClickListener(new MyClickListener(param));
// in a separate class file:
public class MyClickListener extends View.OnClickListener{
private Param param;
public MyClickListener(Param p){
this.param = p;
}
@Override
public void onClick(View v) {
// Do something clever with param
}
}
The nice thing about anonymous classes is that they can directly use all instance fields and final local variables from the scope they're defined in, saving you the effort to write and maintain all that parameter-passing and -keeping code.
Well, you could make a top level class (a class in a new file), or you could embed the class as an inner class into the one using it.
Here is a top level class:
public class MyOnClickListener implements View.OnClickListener {
public void onClick(View v) {
//do something
}
}
Here is an embedded class:
public class MyActivity extends Activity {
class MyOnClickListener implements View.OnClickListener {
public void onClick(View v) {
//do something
}
}
}
精彩评论