如何在android应用程序中将案例作为字符串重写为开关?

时间:2015-03-28 09:32:40

标签: android if-statement switch-statement

我正在检测我点击了哪个按钮:

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

1 个答案:

答案 0 :(得分:2)

请使用此:

public void onClick(View v) {

switch(v.getId()){

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

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

如果这不起作用,请尝试:

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