user3845866
user3845866

Reputation: 23

Perform action only if two buttons are clicked

This is the first time I'm ever dabbling in Android development so please bear with me.

My requirement is this:

I have two buttons on screen, A and B. If the user presses both buttons (order doesn't matter), I need another page to be displayed. Pressing either A or B should do nothing.

Is this possible? If so, how would I achieve this?

Thank you.

Upvotes: 0

Views: 111

Answers (2)

Nikola Tesla
Nikola Tesla

Reputation: 31

This is possible if you take a flag. (boolean) You should set a flag in your button listeners.

    public class Mtest extends Activity {
      Button b1;
      Button b2;
      boolean flag_1 = false;
      boolean flag_2 = false;
      public void onCreate(Bundle savedInstanceState) {
        ...
        b1 = (Button) findViewById(R.id.b1);
        b2 = (Button) findViewById(R.id.b2);
        b1.setOnClickListener(myhandler1);
        b2.setOnClickListener(myhandler2);

      }
      View.OnClickListener myhandler1 = new View.OnClickListener() {
        public void onClick(View v) {
          // it was the 1st button
          flag_1 = true;
          doSomething();
        }
      };

      View.OnClickListener myhandler2 = new View.OnClickListener() {
        public void onClick(View v) {
          // it was the 2nd button
          flag_2 = true;
          doSomething();
        }
      };



    }

    public void doSomething(){
       if(flag_1 && flag_2)
       {
         //DO SOMETHING
       }
    }
}

Upvotes: 1

Ethan
Ethan

Reputation: 225

Create two boolean's like button1isClickedand button2isClicked,then set an onClickListener for each Button. When the the Button is clicked set the value of these two boolean's to true, then simply create an if() statement that will chekc to see if both buttons have been clicked, like this:

if(button1isClicked == true && button2isClicked == true){
//display your new page
}

Upvotes: 0

Related Questions