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?
Five Ways to Wire Up an Event Listener is a great article overviewing the various ways to set up a single event listener. Let me expand that here for multiple listeners.
1. Member Class
2. Interface Type
3. Anonymous Inner Class
4. Implementation in Activity
5. Attribute in View Layout for OnClick Events
And in xml:
In addition to Cristian C's answer (sorry, I do not have the ability to make comments), if you make one handler for both buttons, you may directly compare v to b1 and b2, or if you want to compare by the ID, you do not need to cast v to Button (View has getId() method, too), and that way there is no worry of cast exception.
Another way of doing it is a single listener from activity , like this:
I Like to do it with single IF instead of switch-else, but if you prefer that, then you should do:
Or you can try the same but without listeners. On your button XML definition:
And in your code define the method
ButtonOnClick
:If you don't want to save instances of the 2 button in the class code, follow this BETTER way (this is more clear and fast!!) :