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?
You will learn the way to do it, in an easy way, is:
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(myhandler1);
b2.setOnClickListener(myhandler2);
...
}
View.OnClickListener myhandler1 = new View.OnClickListener() {
public void onClick(View v) {
// it was the 1st button
}
};
View.OnClickListener myhandler2 = new View.OnClickListener() {
public void onClick(View v) {
// it was the 2nd button
}
};
}
Or, if you are working with just one clicklistener, you can do:
View.OnClickListener myOnlyhandler = new View.OnClickListener() {
public void onClick(View v) {
switch(v.getId()) {
case R.id.b1:
// it was the first button
break;
case R.id.b2:
// it was the second button
break;
}
}
}
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.
Or you can try the same but without listeners. On your button XML definition:
android:onClick="ButtonOnClick"
And in your code define the method ButtonOnClick
:
public void ButtonOnClick(View v) {
switch (v.getId()) {
case R.id.button1:
doSomething1();
break;
case R.id.button2:
doSomething2();
break;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With