Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 323
TJA Avatar asked Mar 15 '12 10:03

TJA


2 Answers

     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.
like image 167
Jake Graham Arnold Avatar answered Oct 15 '22 09:10

Jake Graham Arnold


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;


}
like image 45
Blackbelt Avatar answered Oct 15 '22 11:10

Blackbelt