-2

OnClickListener best practices?

What is best practice if you have an Activity with, let's say 10 buttons, should you create the OnClickListener for each View (Button) or is it better to create a single onClickListener and just use a switch with the view ID to determine the clicked View?

Mohammad Ersan
  • 12,304
  • 8
  • 54
  • 77
Solx85
  • 244
  • 2
  • 16

4 Answers4

5
@Override
public void onClick(View v) {
   switch (v.getId()) {
      case R.id.btn_1:
         //Logic_1
      break;
      case R.id.btn_2:
         //Logic_2
      break;
   }
}
Cryperian
  • 116
  • 1
  • 8
2

If you search a little in Google or StackOverflow..

Multiple Buttons `OnClickListener()` android

Best solution is switch:

@Override
public void onClick(View v) {

    switch (v.getId()) {

        case R.id.oneButton:
            // do your code
            break;

        case R.id.twoButton:
            // do your code
            break;

        case R.id.threeButton:
            // do your code
            break;

        default:
            break;
    }

}
Community
  • 1
  • 1
adalpari
  • 3,052
  • 20
  • 39
2

I know that you know code therefore i can say only:

Switch is better as a case or switch statement is considered easier to read and maintain

It is more manageable for having higher level of indentation than if.

Androider
  • 3,833
  • 2
  • 14
  • 24
  • 1
    This was probably the only answer that was to the point, I know the code and did not ask for examples but merely in practice what is the better choice. Thanks for some actual advice! – Solx85 Sep 15 '16 at 11:07
  • I am happy to help you. Thanks. – Androider Sep 15 '16 at 11:08
1

you can use any thing which you like to use because as computational point both are same but if you want to sort your line of code then use signal with switch case

for references see this Multiple Buttons `OnClickListener()` android

Community
  • 1
  • 1
shubham goyal
  • 537
  • 3
  • 3