Ayohaych
Ayohaych

Reputation: 5189

Android better way to do button clicks?

So right now I'm tidying up some code, and I have a lot of else/ifs for buttons and was wondering what is a good way to do it and make it neater?

So I have like 12 buttons, and each button plays a sound and changes colour when clicked. I have a method for this but I was wondering is there a good way to just detect the button instead of if/else?

public void onClick(View v) {
    int id = v.getId();
    changeToWhite();
    if (id == R.id.a_button) {
        currentButton(a, 81);
    } else if (id == R.id.aSharp_button) {
        currentButton(aSharp, 82);
    } else if (id == R.id.b_button) {
        currentButton(b, 83);
    } else if (id == R.id.c_button) {
        currentButton(c, 72);
    }

Etc...

So is there a better way of having this? I know having a lot of else/ifs is bad so I wanted to try improve it. Thanks!!

Upvotes: 0

Views: 365

Answers (4)

sebster
sebster

Reputation: 1320

First of all there is virtually no penalty for using if/else nesting. There's no need to try this level of micromanaging your app. You will gain no benefits from it. Try to think more of optimizing this point in terms of readability.

Now, to answer your question, you could use a switch/case construct instead.

public void onClick(View v) {
    switch (item.getItemId()) {

        case R.id.aBar_item1:
         //Item onClick logic
         return true;

        case R.id.aBar_item2:
        //Item onClick logic
        return true;

        case R.id.aBar_item3:
        //Item onClick logic
        return true;

        ...
    }  
}

Upvotes: 1

alex
alex

Reputation: 6409

I assume you're using XML and setting the onClick property.

An easier/tidier way is to use anonymous inner classes.

public void onCreate(Bundle savedInstanceState){
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_foo);

    findViewById(R.id.view_buttonone).setOnClickListener(new OnClickListener(){
        public void onClick(View view){
            // button one clicked
        }
    });

    findViewById(R.id.view_buttontwo).setOnClickListener(new OnClickListener(){
        public void onClick(View view){
            // button two clicked
        }
    });
}

Upvotes: 1

user1357851
user1357851

Reputation:

How about using a case statement instead?

    public void onClick(View v) {
       // Perform action on click
      switch(v.getId()) {
        case R.id.a_button:
          currentButton(a, 81);
          break;
        case R.id.aSharp_button:
          currentButton(aSharp, 82);
          break;
        /*
          and the rest of the cases here.
        */

      }
   }

Upvotes: 1

tungdx
tungdx

Reputation: 108

You can use "switch-case" instead.

>

public void onClick(View v) {
switch(v.getId())
{
case R.id.a_button:
changeToWhite();
break;
case R.id.aSharp_button:
currentButton(aSharp,82);
break;
.....
default:
break;
}

}

Upvotes: 2

Related Questions