Let’s say I have a method like this into my activity, and set it as onClick field of different buttons into xml:
public void onButtonPressedFromView(View button) {
switch(button.getId()) {
case (R.id.button1) :
//do something
break;
case (R.id.button2) :
//do something different
break;
default :
//default action
break;
}
}
It comes out that, if I press for instance button1, the id obtained with button.getId() is always bigger of 1 than the id obtained with R.id.button1. It’s quite easy to solve, I just changed my code into
switch(button.getId() - 1)
but I don’t like it, and would like to understand the difference between these two ways of obtaining the id of a view.
You should be comparing known buttons to the presses.
It is important to not assume myButton == button. For instance, if you use a button in a ListView it will likely have several instances and can thus only be comparable by the getId() property.