Omer Faruk Celebi
Omer Faruk Celebi

Reputation: 268

Programming convention on Anonymous Class vs Implementing Interface

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) {

}
}

Upvotes: 7

Views: 676

Answers (3)

Dheeresh Singh
Dheeresh Singh

Reputation: 15701

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.

Upvotes: 3

joval
joval

Reputation: 506

Well, there isn't really much differences between both except one: in second case you have access to onClick(View v) method from outside the class.

If it comes to me I prefer first approach, because not often more than one component have at the same time the same behaviour on click.

Upvotes: 0

Samir Mangroliya
Samir Mangroliya

Reputation: 40416

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.

Upvotes: 4

Related Questions