3

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??

Phantômaxx
  • 37,901
  • 21
  • 84
  • 115
  • 2
    There is no answer to this. It depends on your usecase. Also you should NOT call an Object instance with an update cased First Character. Instead of Btn it should button. – JoxTraex Nov 12 '17 at 05:58
  • Implementing interface is good practice if you many clickable Items . Read [This](https://stackoverflow.com/questions/19718353/is-repeatedly-instantiating-an-anonymous-class-wasteful) thread . You will get the idea . – ADM Nov 12 '17 at 06:01

1 Answers1

2

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

Abdul Waheed
  • 4,540
  • 6
  • 35
  • 58