TJA
TJA

Reputation: 53

switch onClick buttons

I have three buttons

Button1 btn1 = (Button) findViewById(R.id.button1);
Button2 btn2 = (Button) findViewById(R.id.button2);
Button3 btn3 = (Button) findViewById(R.id.button3);

btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);

public void onClick(View v) {

switch(v){
 case bt1:
 //SOME CODE
 break;
 case bt2:
 //SOME CODE
 break;
 case bt3:
 //SOME CODE
 break;


}

It breaks when it gets to the switch, can anyone help me? first post hope everythings ok

Upvotes: 5

Views: 770

Answers (2)

Jake Graham Arnold
Jake Graham Arnold

Reputation: 1446

     public void onClick(View v) {

     switch(v.getId()){
     case R.id.button1:
     //SOME CODE
     break;
     case R.id.button2:
     //SOME CODE
     break;
     case R.id.button3:
     //SOME CODE
     break;
 }
  • The view is passed into the onClick
  • Therefore switch should look for the view, not the button name.

Upvotes: 5

Blackbelt
Blackbelt

Reputation: 157437

change it in

    Button1 btn1 = (Button) findViewById(R.id.button1);
Button2 btn2 = (Button) findViewById(R.id.button2);
Button3 btn3 = (Button) findViewById(R.id.button3);

btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);

public void onClick(View v) {

switch(v.getId()){
 case R.id.button1:
 //SOME CODE
 break;
 case R.id.button2:
 //SOME CODE
 break;
 case R.id.button3:
 //SOME CODE
 break;


}

Upvotes: 5

Related Questions