Reputation: 61
There are 2 ways to use OnClick event in android studio.
First method is,
Btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
}
};
Second way is,
in MainActivity
Btn.setOnClickListener(this);
and Override method onClick
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button1:
// do stuff;
break;
case R.id.button2:
// do stuff;
break;
...
}
What is the best and most efficient way from above two??
Upvotes: 3
Views: 853
Reputation: 4678
Both are good. Nothing in wrong on above mentioned methods. But I would prefer second one with switch statements when I have to listen click events with many views on the other hand If want to listen click event for a view or two I prefer to use first one. NOTE: If click events are more than to implement anonymous way (as you implemented in first example) the line of code increases a lot. It looks tedious and to maintain code becomes harder. But other developer may feel comfortable with this
Upvotes: 2