Enable 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 comes to the switch, can someone help me? first post hope everything is fine

+5
source share
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;
 }
  • View passed to onClick
  • Therefore, the switch should look for the view, not the name of the button.
+5
source

change it to

    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;


}
+5
source

All Articles