How to determine which button pressed on android
Solution 1:
Most ellegant pattern to follow:
public void onClick(View v) {
switch(v.getId())
{
case R.id.button_a_id:
// handle button A click;
break;
case R.id.button_b_id:
// handle button B click;
break;
default:
throw new RuntimeException("Unknow button ID");
}
This way it's much simplier to debug it and makes sure you don't miss to handle any click.
Solution 2:
I have 10 buttons performing the same method updateText()
, I used this code to get the clicked button's text:
public void updateText(View v){
Button btn = (Button) findViewById(v.getId());
String text = btn.getText().toString();
}
Solution 3:
OR... you can just put a android:onClick="foo" in the xml code of the button, and define a method on java with the signature. Inside the method foo, get the id and compare it with the one you need
public void foo(View v){
if (v.getId() == R.id.yourButton){
}
else if (v.getId() == R.id.nextButton){
}
}
Solution 4:
If by "performing the same method" you mean theirs OnClickListener then you have to reference the parameter being passed to it.
public void onClick(View v) {
if(v==btnA) {
doA();
} else if(v==btnB) {
doB();
}
}