From the android development perspective, while you are programming which way do you prefer to implement for listener? Or which way do you think is the best for readable code? I gave two example about these things but think more complex classes such as which has more than one Listener:)
First example which is an Anonymous Class:
public class SenderReceiverActivity extends Activity {
Button cancelButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sending);
cancelButton = (Button) findViewById(R.id.button1);
cancelButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
}}
Second example which is implementing interface :
public class SenderReceiverActivity extends Activity implements OnClickListener {
Button cancelButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sending);
cancelButton = (Button) findViewById(R.id.button1);
cancelButton.setOnClickListener(this);
}
public void onClick(View v) {
}
}
A normal class can implement any number of interfaces but the anonymous inner class can implement only one interface at a time.
Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. They are like local classes except that they do not have a name. Use them if you need to use a local class only once.
A nested class that doesn't have any name is known as an anonymous class. An anonymous class must be defined inside another class. Hence, it is also known as an anonymous inner class. Its syntax is: class outerClass { // defining anonymous class object1 = new Type(parameterList) { // body of the anonymous class }; }
if you have single button then first approch is right because there are no any complexity in your code but when you have many button then second is more clear ,just one onClick method for many buttons and check id of button using v.getId()
But there are no any change in functionality both are identical.
I think 2nd approch is good as
1- you can handle multiple Views click at one place...
2- it make code shorter and easy to read..
3- it is easy in maintenance.
4- if you are using the Base Activity like concept in your project then it is also useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With