0

I m detecting which button i clicked:

public void next_page(View view){

    //if else - works:

    if( view.getId() == "fly_button")        
            Log.d(LOG, " fly button clicked");
    else if (view.getId() == "imageButton") 
            Log.d(LOG, "image button clicked");

    //switch does not work:
   // every id is a string, how to show it as integer in "case"?

    switch(  view.getId()  ){
        case "fly_button":
            Log.d(LOG, "fly button clicked");
        case "imageButton":
            Log.d(LOG, "image button clicked");
    }      
ERJAN
  • 23,696
  • 23
  • 72
  • 146
  • Do you want an enum? – Mathemats Mar 28 '15 at 09:34
  • Currently in Android you cannot switch on a String
    check : http://stackoverflow.com/questions/338206/why-cant-i-switch-on-a-string
    – Ankit Bansal Mar 28 '15 at 09:38
  • 1
    Note that you cannot use `==` with strings since they are objects. Because of string interning, your code *might* work sometimes but will fail often. Instead, you should use `equals()`. – Simon Mar 28 '15 at 09:44

1 Answers1

2

Please use this:

public void onClick(View v) {

switch(v.getId()){

  case R.id.Button1: 
    // statements
    break;

  case R.id.Button2:
    // statements
    break;
}
}

If this will not work try this:

int id = view.getId();
if (id == R.id.Button1) {
    action1();
} else if (id == R.id.Button2) {
    action2();
}
Avishek Das
  • 661
  • 1
  • 6
  • 20