Android OnClickListener - identify a button Android OnClickListener - identify a button android android

Android OnClickListener - identify a button


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;      }}


I prefer:

class MTest extends Activity implements OnClickListener {    public void onCreate(Bundle savedInstanceState) {    ...    Button b1 = (Button) findViewById(R.id.b1);    Button b2 = (Button) findViewById(R.id.b2);    b1.setOnClickListener(this);    b2.setOnClickListener(this);    ...}

And then:

@Overridepublic void onClick(View v) {    switch (v.getId()) {        case R.id.b1:            ....            break;        case R.id.b2:            ....            break;    }   }

Switch-case is easier to maintain than if-else, and this implementation doesn't require making many class variables.