Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Effectivity, Android switch or click listener for each button

I cant found the topic, perhaps someone can teach me some about android effectivity when the topis is about onclicklistener for buttons.

Lets say I got 10 buttons on a page (just an example now) What's the best thing to do?

  1. A switch that switch id for the buttons?
  2. A onClickListener for each button?

What method is the faster one, and why? Is there any different at all?

like image 624
Andreas Gustafsson Avatar asked Oct 09 '22 07:10

Andreas Gustafsson


2 Answers

Best practice is to go with 1st option: A switch that switch id for the butttons.

As per my experience, i would suggest you to assign android:onClick attribute with same value, say for example: android:onClick="btnClicker"

And now you have to implement the same method inside the activity class as:

public void btnClicker(View v)
{
   switch(v.getId())
   { 
    case R.id.btn1:
         break;

    case R.id.btn2:
         break;

    case R.id.btn3:
         break;
   }
}

About 2nd option: I don't prefer it because it increase number of code lines because just think you are having 10 buttons and you assign separate click listener for each buttons. And now compare it with the above 1st option, you will realize it.

So i would suggest you to go with 1st option i have suggested with example above, main reason is it decrease number of code lines and better readability of code.

Why there is better readability in 1st option i have suggested above?

Because you know you just have to check this particular function only for the code for every buttons, because everything is here inside a function.

like image 60
Paresh Mayani Avatar answered Oct 11 '22 21:10

Paresh Mayani


I would be surprised if there is any significant difference. I would go with #2 because I think it leads to clearer code.

like image 26
Caner Avatar answered Oct 11 '22 20:10

Caner