简体   繁体   English

按下按钮后的开关状态

[英]Switch Statement with Button pressed

So I push either button1, button2, button3, or button4. 因此,我按下了button1,button2,button3或button4。 Pushing any of these Buttons calls method buttonPressed(View v). 按下任何这些Button都会调用方法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. 我不能在视图中使用switch语句。 What is the easiest and most efficient solution to this problem? 最简单,最有效的解决方案是什么? Thanks!! 谢谢!!

Note: I am using android:onClick="buttonPressed" in my .xml 注意:我在.xml中使用了android:onClick =“ buttonPressed”

You need to switch on the View's ID, not the View itself 您需要打开视图的ID,而不是视图本身

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 按下按钮以切换活动时强制关闭 - Force close when button to switch activities is pressed 按下时如何切换按钮的状态 - How to switch the state of a button when pressed 按下主页按钮后,我得到了活动开关 ANDROID - After Home Button get pressed i got activities switch ANDROID 当我按下主页按钮或切换到其他应用程序时应用程序重新启动 - Apps restarts when I pressed home button or switch to other App 使用SWITCH调用不同的意图,具体取决于所按下的按钮 - Using SWITCH to call different intents depending on what button was pressed Android:如何以编程方式切换按钮的按下状态? - Android: how to switch button's pressed state programmatically? 使用 Switch 语句处理按钮点击 - Using Switch Statement to Handle Button Clicks 使用imageButtons切换活动。 如何在按下按钮的第二个活动中切换图像? - Using imageButtons to switch activities. How can I switch image in second activity based on button pressed? 更改和设置按钮背景色,并比较使用开关和外壳按下的按钮的点击次数 - Changing and setting button background color and also comparing clicks on button pressed using switch and case 当按下设备后退按钮时,如何从一项活动切换到另一项指定的活动? - How to switch from an activity to another designated one when the device back button is pressed?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM