[英]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.