Android: Use a SWITCH statement with setOnClickListener/onClick for more than 1 button?

Hubert picture Hubert · Oct 1, 2009 · Viewed 185.4k times · Source

Let's say I have a few buttons in a LinearLayout, 2 of them are:

mycards_button = ((Button)this.findViewById(R.id.Button_MyCards));
exit_button = ((Button)this.findViewById(R.id.Button_Exit));

I register setOnClickListener() on both of them:

mycards_button.setOnClickListener(this);
exit_button.setOnClickListener(this);

How do I make a SWITCH to differentiate between the two buttons within the Onclick ?

public void onClick(View v) {
  switch(?????){
    case ???:
      /** Start a new Activity MyCards.java */
      Intent intent = new Intent(this, MyCards.class);
      this.startActivity(intent);
      break;
    case ???:
      /** AlerDialog when click on Exit */
      MyAlertDialog();
      break;
}

Answer

Intrications picture Intrications · Oct 1, 2009

Use:

  public void onClick(View v) {

    switch(v.getId()){

      case R.id.Button_MyCards: /** Start a new Activity MyCards.java */
        Intent intent = new Intent(this, MyCards.class);
        this.startActivity(intent);
        break;

      case R.id.Button_Exit: /** AlerDialog when click on Exit */
        MyAlertDialog();
        break;
    }
}

Note that this will not work in Android library projects (due to http://tools.android.com/tips/non-constant-fields) where you will need to use something like:

int id = view.getId();
if (id == R.id.Button_MyCards) {
    action1();
} else if (id == R.id.Button_Exit) {
    action2();
}