Manoj Kumar
Manoj Kumar

Reputation: 11

If one button press does something, other buttons pressed should do something else

I have 5 Buttons in an activity. My code should work as follows : 1 (Correct) button pressed it should do something. other 4 pressed, something else should be done... I don't want to used 5 onclicklistener

if(Button1 press) {
    do something
}

else if (button2 or button3 or button4 or button5 press)
{
    something else to do
}

Upvotes: 1

Views: 18719

Answers (3)

codeMagic
codeMagic

Reputation: 44571

There are several ways to do it but if the same buttons will always do the same thing then you can set the onClick() in your xml.

First, define the same function for each Button

<Button
     android:id="@+id/button1"
       ....
     android:onClick="functionName"/>
<Button
     android:id="@+id/button2"
       ....
     android:onClick="functionName"/>

then in your code

public void functionName(View v)
{
    switch (v.getId())   // v is the button that was clicked
    {
       case (R.id.button1):  // this is the oddball 
       ...do stuff
       break;
    default:   // this will run the same code for any button clicked that doesn't have id of button1 defined in xml
        ...do other stuff
    break;
    }
}

now your Buttons or onClickListeners don't have to be defined in your code unless you need to do something else with a Button

Edit

@prosperK has pointed out that with the newer ADT passing int to the switch causes errors so you may need an if/else if this is the case. link to SO post about this

Upvotes: 4

ohaleck
ohaleck

Reputation: 671

Why don't you do it this way:

final Button button1 = (Button) findViewById(R.id.button1);
final Button button2 = (Button) findViewById(R.id.button2);
final Button button3 = (Button) findViewById(R.id.button3);
final Button button4 = (Button) findViewById(R.id.button4);
final Button button5 = (Button) findViewById(R.id.button5);

OnClickListener listener = new OnClickListener() {
    @Override
    public void onClick(View v) {
        if (v.equals(button1)) {
            // do something
        } else {
            // do something else
        }
    }
};

button1.setOnClickListener(listener);
button2.setOnClickListener(listener);
button3.setOnClickListener(listener);
button4.setOnClickListener(listener);
button5.setOnClickListener(listener);

Upvotes: 7

ACengiz
ACengiz

Reputation: 1315

You can define two different click listeners. Button 1 gets first listener and others get the second one. Hope this helps.

Upvotes: 1

Related Questions