Hey. I have the activity:
public class Mtest extends Activity {
Button b1;
Button b2;
public void onCreate(Bundle savedInstanceState) {
...
b1 = (Button) findViewById(R.id.b1);
b2 = (Button) findViewById(R.id.b2);
b1.setOnClickListener(myhandler);
b2.setOnClickListener(myhandler);
...
}
View.OnClickListener myhandler = new View.OnClickListener() {
public void onClick(View v) {
// MY QUESTION STARTS HERE!!!
// IF b1 do this
// IF b2 do this
// MY QUESTION ENDS HERE!!!
}
}
}
How do I check which button has been clicked?
I prefer:
And then:
Switch
-case
is easier to maintain thanif
-else
, and this implementation doesn't require making many class variables.You will learn the way to do it, in an easy way, is:
Or, if you are working with just one clicklistener, you can do:
Though, I don't recommend doing it that way since you will have to add an
if
for each button you use. That's hard to maintain.The best way is by
switch
-ing between v.getId(). Having separate anonymous OnClickListener for each Button is taking up more memory. Casting View to Button is unnecessary. Using if-else when switch is possible is slower and harder to read. In Android's source you can often notice comparing the references by if-else:I don't know exactly why they chose this way, but it works too.
Check this article for more details
use setTag();
like this: