按下按钮切换语句

时间:2013-09-07 01:49:17

标签: android button view switch-statement

所以我按下button1,button2,button3或button4。按下任何这些按钮调用方法buttonPressed(查看v)。我想根据按下的按钮使用不同的情况。例如:

public void buttonPressed(View v){
switch(v){
case button1:
//do something
case button2:
//do something
case button3:
//do something
case button4:
//do something
}}

显然,这不起作用。我不能在视图中使用switch语句。解决这个问题的最简单,最有效的解决方案是什么?谢谢!

注意:我在.xml中使用android:onClick =“buttonPressed”

2 个答案:

答案 0 :(得分:3)

您需要打开View的ID,而不是View本身

public void buttonPressed(View v){
    switch(v.getId()) {
    case R.id.ButtonOneID:
        //do something
        break;
    case R.id.ButtonTwoID:
        //do something
        break;
    case R.id.ButtonThreeID:
        //do something
        break;
    case R.id.ButtonFourID:
        //do something
        break;
    }
}

答案 1 :(得分:2)

public void buttonPressed(View v){
    int id = v.getId();
    switch(id){
    case button1.getId();
        //do something
        break;
    case button2.getId();
        //do something
        break;
    case button3.getId();
        //do something
        break;
    case button4.getId();
        //do something
        break;
    }
}