简体   繁体   中英

Switch Statement with Button pressed

So I push either button1, button2, button3, or button4. Pushing any of these Buttons calls method buttonPressed(View v). I want to use a different case depending on the button pressed. For example:

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

Obviously, this does not work. I cannot use a switch statement with a View. What is the easiest and most efficient solution to this problem? Thanks!!

Note: I am using android:onClick="buttonPressed" in my .xml

You need to switch on the View's ID, not the View itself

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM